添加两个列表然后 sort = None(?) [英] add two lists then sort = None(?)

查看:39
本文介绍了添加两个列表然后 sort = None(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第二个列表将列表中的每个项目平方,xs.运行下面的代码,python 给了我 'None'

Second list squared each item on list, xs. Running the code below, python gives me 'None'

xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')

相同的列表但不同的代码--

Same list but different code--

xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = a + xs
c.sort()
print(c, end=', ')

...python 给了我我的列表(c),全部排序.我不明白.或者有没有更pythonic的方法来做到这一点?

...python gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this?

谢谢!

推荐答案

一般来说,按照约定,任何对就地进行操作的操作都将返回 None.(但是,不一定总是遵循此约定.) somelist.sort() 将就地对列表进行排序.

Generally speaking, anything that operates on something in-place will return None, by convention. (This convention is not necessarily always followed, however.) somelist.sort() will sort the list in-place.

如果您想要一个有序的副本,您可以调用c = sorted(a + xs).sorted 对原始副本进行操作,因此返回副本.

If you'd rather have a sorted copy, you can just call c = sorted(a + xs). sorted operates on a copy of the original, and therefore returns the copy.

这里有更多解释:http://wiki.python.org/moin/HowTo/排序/

这篇关于添加两个列表然后 sort = None(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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