Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将列表项值与其他列表中的其他项进行比较_Python_Plone_Zope - Fatal编程技术网

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

在Python中将列表项值与其他列表中的其他项进行比较,python,plone,zope,Python,Plone,Zope,我想将一个列表中的值与第二个列表中的值进行比较,并返回第一个列表中但不在第二个列表中的所有值,即 list1 = ['one','two','three','four','five'] list2 = ['one','two','four'] 将返回“三”和“五” 我对python只有一点经验,因此这可能是一种荒谬而愚蠢的解决方法,但这就是我迄今为止所做的: def unusedCategories(self): unused = [] for category in self

我想将一个列表中的值与第二个列表中的值进行比较,并返回第一个列表中但不在第二个列表中的所有值,即

list1 = ['one','two','three','four','five']
list2 = ['one','two','four']
将返回“三”和“五”

我对python只有一点经验,因此这可能是一种荒谬而愚蠢的解决方法,但这就是我迄今为止所做的:

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

但是,这会引发一个错误“非序列上的迭代”,我认为这意味着一个或两个“列表”实际上不是列表(两者的原始输出与我的第一个示例的格式相同)

使用集合来获取列表之间的差异:

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

集合(列表1)。差异(集合(列表2))

您可以使用集合或列表来完成:

unused = [i for i in list1 if i not in list2]
与:


您可以跳过将列表2转换为set。

这里的所有答案都是正确的。如果列表很短,我会使用列表理解;集合将更有效率。在探索代码为什么不工作时,我没有发现错误。(这不起作用,但这是另一个问题)

问题是,
if
语句毫无意义。
希望这能有所帮助。

当我直接在中输入示例列表时,这会起作用,但当我尝试使用自动列表(例如list1=self.catList)时,这不会起作用-再次使用非序列错误上的迭代,这是否意味着self.catList没有真正提供列表?这对我来说很好,而且很简单,所以我想我现在就坚持使用这个列表,谢谢大家的迅速帮助input@chrism:您是在暗示此处发布的其他内容很复杂吗?不是,但也许我太简单了,无法理解为什么我首先尝试的其他内容的实现不起作用?我知道这很旧,但是否有人有将项字符串转换为Unicode的问题?
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1).difference(list2)
{'five', 'three'}
>>> list1 = ['a','b','c']
>>> list2 = ['a','b','d']
>>> [c for c in list1 if not c in list2]
['c']
>>> set(list1).difference(set(list2))
set(['c'])
>>> L = list()
>>> for c in list1:
...     if c != L in list2:
...         L.append(c)
... 
>>> L
[]