简体   繁体   English

如何迭代两个不同长度的列表而不合并它们

[英]How to iterate over two lists of different length without combining them

Is there a way to iterate over two lists of different length at the same time without combining them?有没有办法同时迭代两个不同长度的列表而不将它们组合起来?

I tried itertools.product(list1, list2) but that's very similar to a nested loop.我尝试了itertools.product(list1, list2)但这与嵌套循环非常相似。 So the second list gets iterated for each item of the first list, which is not what I want.所以第二个列表会针对第一个列表的每个项目进行迭代,这不是我想要的。

I want to compare both lists and see if they match.我想比较两个列表,看看它们是否匹配。

If your purpose is to check for differences, you can use set s.如果您的目的是检查差异,则可以使用set s。 Let's say you have two lists, like假设您有两个列表,例如

a=["one", "two", "three"]
b=["one", "other"]

You can check the difference by converting them to set:您可以通过将它们转换为设置来检查差异:

print(set(a) - set(b))

The order matters: the first item is the one you are checking against the second:顺序很重要:第一项是您要检查的第二项:

print(set(a) - set(b)) returns {'three', 'two'} (the items present in the first set that are missing in the second), while print(set(a) - set(b))返回{'three', 'two'} (第一组中存在的项目在第二组中缺失),而

print(set(b) - set(a)) returns {'other'} print(set(b) - set(a))返回{'other'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM