从Python列表中删除列表 [英] Remove list from list in Python

查看:94
本文介绍了从Python列表中删除列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
Get difference from two lists in Python

什么是简化的方法?我一直在独自尝试,但无法弄清楚. 列表a和列表b,新列表应具有仅在列表a中的项目.所以:

What is a simplified way of doing this? I have been trying on my own, and I can't figure it out. list a and list b, the new list should have items that are only in list a. So:

a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon

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

I tried writing code, but every time it always returns the whole list a to me.

推荐答案

您可以使用列表理解可以从字面上告诉我们哪些元素需要以new_list结尾:

You can write this using a list comprehension which tells us quite literally which elements need to end up in 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循环:

Or, using a for loop:

new_list = []
for fruit in a:
    if fruit not in b:
        new_list.append(fruit)

如您所见,这些方法非常相似,这就是为什么Python还具有列表理解功能以轻松构造列表的原因.

As you can see these approaches are quite similar which is why Python also has list comprehensions to easily construct lists.

这篇关于从Python列表中删除列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆