从Python中删除列表中的列表

Eli*_*iza 24 python list python-2.7

可能重复:
从Python中的两个列表中获得差异

这样做的简化方法是什么?我一直在努力,我无法弄清楚.列出a和列表b,新列表应该包含仅在列表a中的项目.所以:

a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
Run Code Online (Sandbox Code Playgroud)

我尝试编写代码,但每次总是将整个列表返回给我.

Sim*_*ser 29

你可以使用列表推导来编写这个,它清楚地告诉我们哪些元素需要最终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]
Run Code Online (Sandbox Code Playgroud)

或者,使用for循环:

new_list = []
for fruit in a:
    if fruit not in b:
        new_list.append(fruit)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这些方法非常相似,这也是Python为了轻松构建列表而具有列表推导的原因.


Mic*_*per 14

你可以使用一套:

# 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)
Run Code Online (Sandbox Code Playgroud)

UPDATE
作为iurisilvio和mgilson指出,这种方法只适用,如果ab不包含重复,如果元素的顺序并不重要.

  • 我认为“b”到“set”的转换是没有必要的。您还可以使用原始“列表”来执行差异。 (2认同)

mar*_*tin 8

你可能想要这个:

a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]

new_list = [x for x in a if (x not in b)]

print new_list
Run Code Online (Sandbox Code Playgroud)


Ale*_*son 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
Run Code Online (Sandbox Code Playgroud)

或者,更简洁:

new_list = filter(lambda v: v not in b, a)
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,在_更简洁_示例中,“new_list”**不是**列表。它是一个过滤器迭代器。 (3认同)

Stu*_*rey 5

使用Setsset (或者Sets 在 2.6 中被弃用后内置的)怎么样?

from sets import Set
a = Set(['apple', 'carrot', 'lemon'])
b = Set(['pineapple','apple','tomato'])
new_set =  a.difference(b)
print new_set
Run Code Online (Sandbox Code Playgroud)

给出输出

Set(['carrot', 'lemon'])
Run Code Online (Sandbox Code Playgroud)