Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...