简体   繁体   English

用Python理解列表?

[英]List comprehension in Python?

I have this list : 我有这个清单:

a = [1,2,3,4,5] a = [1,2,3,4,5]

I want to delete each element from the list. 我想从列表中删除每个元素。 This is how I'm doing. 我就是这样

for i in range(0,len(a)):
    del a[0] 

Can I use list comprehension in this? 我可以在其中使用列表理解吗? such as del a[0] for i in range(0,len(a)) 例如del a[0] for i in range(0,len(a))

List comprehensions are for creating lists, not destroying them. 列表推导用于创建列表,而不是销毁它们。 They are not the right tool for this job. 他们不是这项工作的正确工具。

If you want to clear the contents of a list, the quickest way is 如果要清除列表的内容,最快的方法是

del a[:]

This is a slice deletion. 这是切片删除。 The omitted beginning and ending points default to the start and end of the list. 省略的起点和终点默认为列表的起点和终点。

Note that frequently, it's better to just replace the list with a new one: 请注意,通常最好将列表替换为新列表:

a = []

This works even if a didn't already exist, and modifications to the new list won't interfere with any other parts of the code that needed the old list. 即使a尚不存在,此方法也有效,并且对新列表的修改不会干扰需要旧列表的代码的任何其他部分。 These attributes are often, though not always, desirable. 这些属性通常(但并非总是)是理想的。

You wouldn't usually do this with a loop at all. 通常您根本不会使用循环来执行此操作。 To clear an existing list, use a[:] = [] . 要清除现有列表,请使用a[:] = []

No, you cannot del components in a list comprehension. 不,您不能在列表推导中del组件。 Why would you want to do that in the first place? 您为什么首先要这样做? A list comprehension is for creating a list, not for modifying. 列表理解是用于创建列表,而不是用于修改。

You can replace the list with a different one created with a list comprehension. 您可以将列表替换为使用列表理解创建的另一列表。

The reason is that a list comprehension needs an expression. 原因是列表理解需要一个表达式。 But del is a statement. 但是del是一个声明。

List comprehension (coming from functional programming, where nothing is ever mutated) is for building lists. 列表理解(来自功能编程,其中什么都没有改变)是用于构建列表的。 Since it appears you want to clear out the elements of an existing list (and not creating a new list with only some of the elements etc.), list comprehension is not the right tool. 由于您似乎想清除现有列表的元素(而不是仅使用某些元素等来创建新列表),因此列表理解不是正确的工具。

That said, list comprehension can be abused to do it: 就是说,列表理解可以被滥用来做到这一点:

[a.pop() for i in range(len(a))]

NOTE: This is a bad idea (since it uses list comprehenstion for something completely different than what it is intended for) and I would strongly recommend you do not use it. 注意:这是一个坏主意(因为它使用列表理解来实现与预期目的完全不同的东西),我强烈建议您不要使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM