开发者

add two lists then sort = None(?) [duplicate]

This question already has answers here: Why do these list methods (append, sort, extend, remove, clear, reverse) return None rather than the resulting list? (6 answers) Closed 6 months ago.

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 gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this?

Thanks!


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.

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.

There's a much more through explanation here: http://wiki.python.org/moin/HowTo/Sorting/


You use generator expressions and itertools to reduce the amount of temporary storage like this

>>> import itertools
>>> xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
>>> a = (b**2 for b in xs)
>>> c = sorted(itertools.chain(a, xs))
>>> c
[3, 9, 10, 12, 17, 20, 32, 42, 66, 99, 100, 144, 289, 400, 1024, 1764, 4356, 9801]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜