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)]
现在,我想创建一个仅包含1,[(1, 2), (1, 3), (1, 4), (1, 5)]
的new_list。然后创建仅有两个奇数的new_list2
,[(1, 3), (1, 5), (3, 5)]
。
我应该怎么做?提前谢谢。
答案 0 :(得分: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)]
答案 1 :(得分: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)]
答案 2 :(得分: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]
这应该起作用=)
答案 3 :(得分:0)
您可以使用带lambda的过滤器:
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]
是第二个。