Python LIST函数未返回新列表 [英] Python LIST functions not returning new lists

查看:122
本文介绍了Python LIST函数未返回新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑内置的Python List方法时遇到问题.

I'm having an issue considering the built-in Python List-methods.

在学习Python的过程中,我一直认为Python变异子(正如任何值类变异子都应该做的那样)会返回它创建的新变量.

As I learned Python, I always thought Python mutators, as any value class mutators should do, returned the new variable it created.

以这个例子为例:

a = range(5)
# will give [0, 1, 2, 3, 4]
b = a.remove(1)
# as I learned it, b should now be [0, 2, 3, 4]
# what actually happens:
# a = [0, 2, 3, 4]
# b = None

此列表更改器不返回新列表的主要问题是您随后无法再进行多个更改. 假设我想要一个介于0到5之间,不包含2和3的列表. 返回新变量的突变体应该能够做到这一点:

The main problem with this list mutator not returning a new list, is that you cannot to multiple mutations subsequently. Say I want a list ranging from 0 to 5, without the 2 and the 3. Mutators returning new variables should be able to do it like this:

a = range(5).remove(2).remove(3)

不幸的是,这是不可能的,例如range(5).remove(2) = None.

This sadly isn't possible, as range(5).remove(2) = None.

现在,有没有一种方法可以像我想在示例中那样对列表进行多个突变?我认为甚至PHP都允许使用Strings进行这些类型的后续突变.

Now, is there a way to actually do multiple mutations on lists like I wanna do in my example? I think even PHP allows these types of subsequent mutations with Strings.

我也找不到所有内置Python函数的良好参考.如果有人可以找到所有列表mutator方法的实际定义(带有返回值),请告诉我.我只能找到以下页面: http://docs.python.org/tutorial/datastructures.html

I also can't find a good reference on all the built-in Python functions. If anyone can find the actual definition (with return values) of all the list mutator methods, please let me know. All I can find is this page: http://docs.python.org/tutorial/datastructures.html

推荐答案

Python库不是使用两者都是进行突变和返回对象,而是选择了一种使用mutator结果的方法.来自import this:

Rather than both mutating and returning objects, the Python library chooses to have just one way of using the result of a mutator. From import this:

应该有一种-最好只有一种-显而易见的方法.

There should be one-- and preferably only one --obvious way to do it.

话虽如此,您想要做的更常用的Python样式是使用 list comprehensions generator表达式:

Having said that, the more usual Python style for what you want to do is using list comprehensions or generator expressions:

[x for x in range(5) if x != 2 and x != 3]

您也可以将它们链接在一起:

You can also chain these together:

>>> [x for x in (x for x in range(5) if x != 2) if x != 3]
[0, 1, 4]

上面的生成器表达式还有一个优势,它可以在 O(n)时间内运行,因为Python仅对range()进行一次迭代.对于大型生成器表达式,甚至对于无限生成器表达式,这都是有利的.

The above generator expression has the added advantage that it runs in O(n) time because Python only iterates over the range() once. For large generator expressions, and even for infinite generator expressions, this is advantageous.

这篇关于Python LIST函数未返回新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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