2014-10-30 167 views
-2
Numbers = [1, 2, 3, 4, 5] 
x_list = list(itertools.combinations(Numbers, 2)) 
x_list = [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] 

现在,我想创建一个new_list,其中只包含1 [(1, 2), (1, 3), (1, 4), (1, 5)]。然后创建仅有两个奇数的new_list2[(1, 3), (1, 5), (3, 5)]Python 3.4.1 - 嵌套列表中的元素

我应该怎么办?提前致谢。

+0

您遇到过什么问题? – 2014-10-30 17:42:21

回答

0

您可以使用过滤器拉姆达:

Numbers = [1, 2, 3, 4, 5] 
x_list = list(combinations(Numbers, 2)) 
new_list1, new_list2 = list(filter(lambda x: 1 in x, x_list)) ,list(filter(lambda x: x[0] % 2 and x[1] % 2, x_list)) 

如有数模2具有余数,那么该数是奇数,x[0]是每个元组中第一个元素x[1]是第二个。

+0

>>> new_list1,new_list2 = filter(lambda x:x [0] == 1,x_list),filter(lambda x:x [0]%2和x [1]%2,x_list)
>>> new_list1
<在0x00000000036754E0滤镜对象>
>>> new_list2
<滤镜对象在0x0000000003675588>
>>> – 2014-10-30 18:56:39

+0

@MarkConcepcion,忘记你正在使用Python 3中,过滤器是在python迭代器3,从而需要调用'list(filter)' – 2014-10-30 19:02:28

0

您可以使用列表理解:

>>> [i for i in x_list if 1 in i] #contain_one 
[(1, 2), (1, 3), (1, 4), (1, 5)] 


>>> [(k,t) for k,t in x_list if k%2!=0 and t%2!=0] #odd_list 
[(1, 3), (1, 5), (3, 5)] 
0
In [2]: x_list = [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]  

In [3]: one_list = [c for c in x_list if c[0]==1] 

In [4]: one_list 
Out[4]: [(1, 2), (1, 3), (1, 4), (1, 5)] 

In [5]: odd_list = [c for c in x_list if all(i%2==1 for i in c)] 

In [6]: odd_list 
Out[6]: [(1, 3), (1, 5), (3, 5)] 
0
new_list = [a for a in x_list if 1 in a] 
new_list2 = [a for a in x_list if a[0]%2!=0 and a[1]%2!=0] 

这应该工作=)