这样做的简化方法是什么?我一直在努力,我无法弄清楚。 列出a和列表b,新列表应该包含仅在列表a中的项目。所以:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
我尝试编写代码,但每次总是将整个列表返回给我。
答案 0 :(得分:26)
你可以用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也有列表推导能够轻松构建列表。
答案 1 :(得分:14)
您可以使用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
不包含重复项,并且元素的顺序无关紧要时,此方法才有效。
答案 2 :(得分:5)
这对你有用吗?
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)
答案 3 :(得分:4)
你可能想要这个:
a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]
new_list = [x for x in a if (x not in b)]
print new_list
答案 4 :(得分:2)