如何在同一个 for
循环中包含两个变量?
t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]
def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical
for i in range(len(t1)) and for j in range(len(t2)):
...
原文由 Quester 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您想要嵌套 for 循环的效果,请使用:
如果您只想同时循环,请使用:
请注意,如果
x
和y
的长度不同,zip
将截断为最短列表。正如@abarnert 指出的那样,如果您不想截断到最短列表,您可以使用itertools.zip_longest
。更新
基于对“将读取列表“t1”和“t2”并返回所有相同元素的函数”的请求,我不认为 OP 想要
zip
或product
。我认为他们想要一个set
:intersection
set
方法将返回它和另一组共有的所有元素(请注意,如果您的列表包含其他list
,首先将内部的list
s 转换为tuples
以便它们是可哈希的;否则调用set
将失败。)。list
函数然后将集合转回列表。更新 2
或者,OP 可能需要 列表中相同位置的 相同元素。在这种情况下,
zip
将是最合适的,并且它截断为最短列表的事实是您想要的(因为当其中一个元素时,索引 9 处不可能有相同的元素列表只有 5 个元素长)。如果那是您想要的,请执行以下操作:这将返回一个列表,其中仅包含列表中相同且位置相同的元素。