比较两个列表并打印出不相等的元素 [英] compare two lists and print out unequal elements

查看:92
本文介绍了比较两个列表并打印出不相等的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个以下格式的列表:

I have two lists in the following format:

list1 = ['A','B','C','D']
list2 = [('A',1),('B',2),('C',3)]

我想比较两个列表并打印出第三个列表,该列表将在list1中显示那些元素,但在list2中不存在,并且我只想比较list2 [i] [0]元素.

I want to compare the two lists and print out a third list which will have those elements present in list1 but not in list2 and I want to compare only the list2[i][0] elements.

我尝试了以下代码:

fin = [i for i in list1 if i not in list2]

但是它将打印list1中的所有元素.我希望上述情况的输出为:

But it prints all the elements in list1. I want the output in the above case to be :

fin = ['D']

有人可以建议如何做吗? 另外,我也不想将2D数组list2转换为1D数组.

Could somebody please suggest how to do that? Also, I do not want to convert my 2D array list2 to 1D array.

推荐答案

使用设置的差异.

set(list1) - set(i[0] for i in list2)

这篇关于比较两个列表并打印出不相等的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆