在Python中比较列表项的值与其他列表中的项

3 投票
5 回答
4724 浏览
提问于 2025-04-15 19:09

我想把一个列表里的值和另一个列表里的值进行比较,找出那些在第一个列表里但不在第二个列表里的值,也就是说:

list1 = ['one','two','three','four','five']
list2 = ['one','two','four']

这样会返回'three'和'five'。

我对python的了解不多,所以我可能用了一种很傻的方式来解决这个问题,但这是我到目前为止做的:

def unusedCategories(self):
    unused = []
    for category in self.catList:
        if category != used in self.usedList:
            unused.append(category)
    return unused

不过这段代码报了一个错误,提示'iteration over non-sequence',我理解这个意思是说一个或两个'列表'其实并不是列表(它们的原始输出格式和我第一个例子是一样的)。

5 个回答

1

使用 set.difference 的话:

>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1).difference(list2)
{'five', 'three'}

你可以不把 list2 转换成集合。

8

这段代码的意思是,从第一个列表(list1)中找出那些在第二个列表(list2)里没有的元素。简单来说,就是把两个列表里的元素进行比较,看看第一个列表里有什么东西是第二个列表里没有的,然后把这些独特的元素列出来。

6

使用集合来找出两个列表之间的不同之处:

>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1) - set(list2)
set(['five', 'three'])

撰写回答