带条件的两个列表的乘积

2024-10-01 11:38:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一种简洁的方法,从两个列表中构造组合元组列表。考虑以下列表:

x = [1, 2, 3]
y = [0, 3, 4, 5]

目标是获得如下列表:

[(None, 0), (1, None), (2, None), (3, 3), (None, 4), (None, 5)]

因此,匹配对一起进行,如果一个列表中没有对应的元素,那么它应该由某个元素填充(这里,None

zipitertools.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)术语)

有简单的方法吗


Tags: and方法innone元素列表forif
2条回答

list comprehensionset可能会帮助你

x = [1, 2, 3]
y = [0, 3, 4, 5]
x = set(x)
y = set(y)
u = x.intersection(y)
diff = x - y
diff_2 = y - x
t = [(i, None) for i in diff] + [(i, i) for i in u] + [(None, i) for i in diff_2]

print(t)

结果:

[(1, None), (2, None), (3, 3), (None, 0), (None, 4), (None, 5)]

列表理解是一种方法:

[(i if i in x else None, i if i in y else None) for i in range(1, max(x + y) + 1)]

给出:

[(None, 0), (1, None), (2, None), (3, 3), (None, 4), (None, 5)]

相关问题 更多 >