将两个列表组合成一个新列表并进行排序

Lan*_*ins 2 python sorting merge list

shares_1 = [50, 100, 75, 200]
shares_2 = [100, 100, 300, 500]
shares_1.extend(shares_2)
print shares_1
Run Code Online (Sandbox Code Playgroud)

输出[50,100,75,200,100,100,300,500]

我想要的是将一个变量分配给合并列表并对列表进行排序.看到我的错误尝试下面的任何建议?

shares_3.sort() = shares_1.extend(shares_2)
Run Code Online (Sandbox Code Playgroud)

谢谢!

JBe*_*rdo 9

shares_3 = sorted(shares_1 + shares_2)
Run Code Online (Sandbox Code Playgroud)


Jos*_*ews 5

shares_3 = shares_1 + shares_2
shares_3.sort()
Run Code Online (Sandbox Code Playgroud)

或者,

shares_1.extend(shares_2)
shares_1.sort()
Run Code Online (Sandbox Code Playgroud)


sen*_*rle 5

Josh Matthews的回答提供了两种很好的方法.有一些基本原则在这里明白了,但:首先,通常,当你调用改变列表的方法,它不会也返回的改变列表.所以...

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

如您所见,这些方法不返回任何内容 - 它们只是更改它们绑定的列表.另一方面,您可以使用sorted,不会更改列表,而是复制它,对副本进行排序,并返回副本:

>>> shares_1.extend(shares_2)
>>> shares_3 = sorted(shares_1)
>>> shares_3
[50, 75, 100, 100, 100, 100, 100, 200, 300, 300, 500, 500]
Run Code Online (Sandbox Code Playgroud)

其次,请注意,您永远不能分配给函数调用.

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