[英]Finding mismatched item for same index in a python list
I have following lists 我有以下清单
l1 = ['a','b','c','a']
l2 = ['a','d','c','c']
I want to find out elements from l2 which do not match to elements of l1 at the same index. 我想从l2中找出与相同索引处的l1元素不匹配的元素。 eg: output for above list would be ['d','c'] 例如:上面列表的输出为['d','c']
as l2 should have 'b' at 2nd position. 因为l2应该在第二个位置有“ b”。
I can do this by iterating over the list and finding the mismatch. 我可以通过遍历该列表并找到不匹配项来实现。
l3 = []
for i in range(len(l1)):
if l1[i] != l2[i]: l3.append(l2[i])
print l3
Is there any better way to do this. 有没有更好的方法可以做到这一点。 Thanks. 谢谢。
missing = [b for a,b in itertools.izip_longest(l1,l2,fillvalue=object()) if a != b]
比pythonic多一点...但是基本上是一样的
Python list comprehension, without needing to import any modules like itertools. Python列表理解,无需导入任何模块(如itertools)。
l3 = [b for a,b in zip(l1,l2) if b != a]
Whenever you find yourself wanting to do a for loop wherein at each iteration you may be appending to something that started as an empty list, think of using a list comprehension. 每当您发现自己想要进行for循环时,其中在每次迭代时您都可能会将其附加到以空列表开头的内容上,请考虑使用列表理解。
If you have the same size lists you can use enumerate
: 如果您具有相同的尺寸列表,则可以使用enumerate
:
l1 = ['a','b','c','a']
l2 = ['a','d','c','c']
print [ele for ind,ele in enumerate(l2) if ele != l1[ind]]
['d', 'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.