我有两个列表,我想使用 itertool.zip_longest 来比较列表中的一些值并执行其他操作,这是我到目前为止编写的代码
import itertools
List1 = [['a'],['B']]
List2 = ['A','b','C']
for a in List1:
for i in itertools.zip_longest(a,List2):
print (i)
但这就是我得到的结果,我仍在尝试理解这种行为
('a', 'A')
(None, 'b')
(None, 'C')
('B', 'A')
(None, 'b')
(None, 'C')
我正在尝试得到这样的东西
('a', 'A')
('B', 'b')
(None, 'C')
这样我就可以直接比较这些值
最佳答案
您可以使用生成器表达式来展平 list1:
List1 = [['a'],['B']]
List2 = ['A','b','C']
print(list(itertools.zip_longest((b for a in List1 for b in a),List2))
[('a', 'A'), ('B', 'b'), (None, 'C')]
如果您想比较,只需迭代 zip_longest 对象解包:
for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
if a == b:
# do whatever
要设置特定的默认值,请使用 fillvalue:
List1 = [['a'],['B']]
List2 = ['A','b','C']
print(list(itertools.zip_longest((b for a in List1 for b in a),List2,fillvalue="foo")))
[('a', 'A'), ('B', 'b'), ('foo', 'C')]
关于python-3.x - 如何使用 itertools.zip_longest 获取嵌套列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29502527/