我试图找到一种简洁的方法,从两个列表中构造组合元组列表。考虑以下列表:
x = [1, 2, 3]
y = [0, 3, 4, 5]
目标是获得如下列表:
[(None, 0), (1, None), (2, None), (3, 3), (None, 4), (None, 5)]
因此,匹配对一起进行,如果一个列表中没有对应的元素,那么它应该由某个元素填充(这里,None
)
zip
和itertools.zip_longest
在这里不起作用,而且itertools.product
显然返回列表的所有组合,这需要大量的后期筛选才能获得正确的组合
我试过:
prods = product(x, y)
matches = [ (i,j) for prods if i==j ]
unmatches = []
for i, j in prods:
if i != j and (i, None) not in unmatches:
unmatches += [ (i, None) ]
elif i != j and (None, j) not in unmatches:
unmatches += [ (None, j) ]
然而,这返回:
matches
# [(3,3)]
unmatches
# [ (1, None), (None, 3), (None, 4), (None, 5), (2, None), (3, None) ]
因为product
如何返回产品(例如,没有(0, j)
术语)
有简单的方法吗
list comprehension
和set
可能会帮助你结果:
列表理解是一种方法:
给出:
相关问题 更多 >
编程相关推荐