【发布时间】:2012-07-11 04:27:43
【问题描述】:
执行此操作的简化方法是什么?我一直在自己尝试,我无法弄清楚。 列表 a 和列表 b,新列表应该包含仅在列表 a 中的项目。所以:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
我尝试编写代码,但每次它总是将整个列表返回给我。
【问题讨论】:
标签: python list python-2.7
执行此操作的简化方法是什么?我一直在自己尝试,我无法弄清楚。 列表 a 和列表 b,新列表应该包含仅在列表 a 中的项目。所以:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
我尝试编写代码,但每次它总是将整个列表返回给我。
【问题讨论】:
标签: python list python-2.7
你可能想要这个:
a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]
new_list = [x for x in a if (x not in b)]
print new_list
【讨论】:
您可以使用set:
# Assume a, b are Python lists
# Create sets of a,b
setA = set(a)
setB = set(b)
# Get new set with elements that are only in a but not in b
onlyInA = setA.difference(b)
更新
正如 iurisilvio 和 mgilson 所指出的,这种方法只有在 a 和 b 不包含重复项并且元素的顺序无关紧要时才有效。
【讨论】:
a 和b 仅包含唯一条目时,此方法才有效。在这种情况下,无论如何将set 用于a,b 会更有意义。但这可能是最快的方法。
b 到set 的转换是没有必要的。您也可以使用原始的list 执行差异。
【讨论】:
set?
sets 自 Python v2.6 起已弃用(请参阅 docs.python.org/library/sets.html)
sets 模块在内置 set 之前就已经存在了。现在它主要留在那里是为了向后兼容。
您可以使用list comprehension 编写此代码,它可以非常准确地告诉我们哪些元素需要以new_list 结尾:
a = ['apple', 'carrot', 'lemon']
b = ['pineapple', 'apple', 'tomato']
# This gives us: new_list = ['carrot' , 'lemon']
new_list = [fruit for fruit in a if fruit not in b]
或者,使用 for 循环:
new_list = []
for fruit in a:
if fruit not in b:
new_list.append(fruit)
正如您所见,这些方法非常相似,这就是 Python 还具有列表推导以轻松构建列表的原因。
【讨论】:
b 中所有出现在a 中的元素。所以如果a == [1, 1, 1, 2, 3, 4] 和b == [1, 3],那么new_list == [2, 4],而不是例如new_list == [1, 1, 2, 4].
这对你有用吗?
a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]
new_list = []
for v in a:
if v not in b:
new_list.append(v)
print new_list
或者,更简洁:
new_list = filter(lambda v: v not in b, a)
【讨论】:
new_list不是一个列表。这是一个过滤器迭代器。