在Python中将列表项值与其他列表中的其他项进行比较
我想将一个列表中的值与第二个列表中的值进行比较,并返回第一个列表中但不在第二个列表中的所有值,即
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
然而,这会抛出一个错误“非序列迭代”,其中我认为一个或两个“列表”实际上并不是列表(两个列表的原始输出与我的第一个示例的格式相同)
I want to compare the values in one list to the values in a second list and return all those that are in the first list but not in the second i.e.
list1 = ['one','two','three','four','five']
list2 = ['one','two','four']
would return 'three' and 'five'.
I have only a little experience with python, so this may turn out to be a ridiculous and stupid way to attempt to solve it, but this what I have done so far:
def unusedCategories(self):
unused = []
for category in self.catList:
if category != used in self.usedList:
unused.append(category)
return unused
However this throws an error 'iteration over non-sequence', which I gather to mean that one or both 'lists' aren't actually lists (the raw output for both is in the same format as my first example)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
set(list1).difference(set(list2))
set(list1).difference(set(list2))
使用集合来获取列表之间的差异:
Use sets to get the difference between the lists:
使用
set.difference
:你可以跳过要设置的
list2
转换。with
set.difference
:you can skip conversion of
list2
to set.您可以使用集合或列表理解来完成此操作:
You can do it with sets or a list comprehension:
这里的所有答案都是正确的。如果列表很短,我会使用列表理解;集会更有效率。在探索为什么您的代码不起作用时,我没有收到错误。 (这不起作用,但那是另一个问题)。
问题是
if
语句没有任何意义。希望这有帮助。
All the answers here are correct. I would use list comprehension if the lists are short; sets will be more efficient. In exploring why your code doesn't work, I don't get the error. (It doesn't work, but that's a different issue).
The problem is that the
if
statement makes no sense.Hope this helps.