如何在python中消除list2(与另一个list1相同)中的值

如何在python中消除list2(与另一个list1相同)中的值,python,python-3.x,Python,Python 3.x,输入: 输出: list1 = ['name', 'age', 'gender', 'location'] list2 = ['name', 'age'] list3 如何从列表中减去常用元素?使用列表理解 list3 = ['gender', 'location'] 或 一种简单的方法是迭代两个列表中较大的一个,如果在另一个列表中找不到当前元素,则将其追加到最终结果 示例 In [23]: [i for i in list1+list2 if (list1+list2).count(i

输入:

输出:

list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3 

如何从列表中减去常用元素?

使用
列表理解

list3 = ['gender', 'location']


一种简单的方法是迭代两个列表中较大的一个,如果在另一个列表中找不到当前元素,则将其追加到最终结果

示例

In [23]:  [i for i in list1+list2 if (list1+list2).count(i) == 1]
Out[23]: ['gender', 'location']
输出:[“性别”、“位置”]

希望这有帮助

使用集合

list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
res = []
for l in list1:
    if l not in list2:
        res.append(l)
print res

beginers的一种简单方法:

list3 = list(set(list1)^set(list2))
这样,您就可以捕获整个差异。如果外循环中的列表比内循环中的列表短,则会丢失一些元素

随着您的进步,您将学习其他方法,如设置差异:
list(set(list1)-set(list2))
,列表理解:
[i为列表1中的i,如果我不在列表2中]
,使用lambdas进行筛选等


从基础开始,了解发生了什么,在学习奇特的方法之前,请尝试以下代码

list1 = some_list
list2 = some_other_list
list3 = []
if len(list1) >= len(list2):
    longer_list = list1
    shorter_list = list2
else:
    longer_list = list2
    shorterlist = list1

for element in longer_list:
    if element not in shorter_list:
        list3.append(element)

此方法类似于@Aidan Dowling答案,即使用。我认为这比使用for循环要好。

如果
list2
的元素比
list1
多,并且其中一些元素不在
list1
中,该怎么办?在这种情况下它将不起作用。您可以执行此操作
list3=list(set(list1)^set(list2))
list1 = some_list
list2 = some_other_list
list3 = []
if len(list1) >= len(list2):
    longer_list = list1
    shorter_list = list2
else:
    longer_list = list2
    shorterlist = list1

for element in longer_list:
    if element not in shorter_list:
        list3.append(element)
In [1]: list1 = ['name', 'age', 'gender', 'location']

In [2]: list2 = ['name', 'age']

In [3]: list3 = list(set(list1) - set(list2))

In [4]: list3
Out[4]: ['gender', 'location']