2014-10-30 211 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] 

這應該工作=)