python 函数返回list 怎么接收,Python LIST函数未返回新列表

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

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

Take this example:

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

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)

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

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.

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

解决方案

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.

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]

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值