简体   繁体   English

如何比较Python的两个列表列表并通过列表中的单个元素删除重复项

[英]How to compare Python two list of lists and remove duplicates by a single element in lists

If you have two list of lists, and you would like to remove lists from one list of lists, that have a matching element for lists in the other list of lists, how do you achieve this? 如果您有两个列表列表,并且想要从一个列表列表中删除列表,而列表列表具有另一个列表列表中与列表匹配的元素,您如何实现此目的?

Say you have 说你有

a = [[a,b,c],[d,e,f]]
b = [[g,h,i],[k,l,m],[n,o,c]]

How do you check the 3rd element in each list in b against the 3rd element in each list in a , and if there is a match then remove the list containing that match from b . 如何将b中每个列表中的第3个元素与b中每个列表中的第3个元素进行a ,如果存在匹配项,则从b删除包含该匹配项的列表。

The desired end result here is 所需的最终结果是

b = [[g,h,i],[k,l,m]]

because "c" is the 3rd element in one of the lists from a , and also is the 3rd element in one of the lists from b , so that list in b is removed. 因为“c”是在从所述列表中的一个的第三元件a ,也是在从所述列表中的一个的第三元件b ,所以在该列表b被除去。

I've tried 我试过了

c = [x for x in b for y in a if not x[2] == y[2]]
c = [y for x,y in zip(a,b) if not x[2] == y[2]]
c = [[x for x in b if not x[2] == y[2]] for y in a]

so far, with all failing. 到目前为止,一切都失败了。

I've researched online and on SOF, and although there might be an answer for this, I've not been able to find one which deals with this specifically. 我已经在网上和SOF上进行了研究,尽管也许可以找到答案,但我仍然找不到能够专门解决这一问题的方法。

This might help. 这可能会有所帮助。

a = [["a","b","c"],["d","e","f"]] 
b = [["g","h","i"],["k","l","m"],["n","o","c"]]

check = [i[2] for i in a]
print([i for i in b if i[2] not in check])

Output : 输出

[['g', 'h', 'i'], ['k', 'l', 'm']]

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

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