开发者

combining two lists into a new list and sorting

shares_1 = [50, 100, 75, 200]
shares_2 = [100, 100, 300, 500]
shares_1.extend(shares_2)
print shares_1

output [50, 100, 75, 200, 100, 100, 300, 500]

What I want is to assign a开发者_JS百科 variable to the merged list and sort the list. See my incorrect attempt below Any suggestions?

shares_3.sort() = shares_1.extend(shares_2)

Thanks!


shares_3 = sorted(shares_1 + shares_2)


Josh Matthews' answer offers two good methods. There are some general principles to understand here, though: First, generally, when you call a method that alters a list, it will not also return the altered list. So...

>>> shares_1 = [50, 100, 75, 200]
>>> shares_2 = [100, 100, 300, 500]
>>> print shares_1.extend(shares_2)
None
>>> print shares_1.sort()
None

As you can see, these methods don't return anything -- they just alter the list to which they are bound. On the other hand, you could use sorted, which does not alter the list, but rather copies it, sorts the copy, and returns the copy:

>>> shares_1.extend(shares_2)
>>> shares_3 = sorted(shares_1)
>>> shares_3
[50, 75, 100, 100, 100, 100, 100, 200, 300, 300, 500, 500]

Second, be aware that you can never assign to a function call.

>>> def foo():
...     pass
... 
>>> foo() = 1
  File "<stdin>", line 1
SyntaxError: can't assign to function call


shares_3 = shares_1 + shares_2
shares_3.sort()

Alternatively,

shares_1.extend(shares_2)
shares_1.sort()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜