Python 将两个列表合并为一个新列表并排序

Python 将两个列表合并为一个新列表并排序,python,list,sorting,merge,Python,List,Sorting,Merge,输出[5010075200100100100300500] 我想要的是为合并列表分配一个变量,并对列表进行排序。看到下面我的错误尝试了吗?有什么建议吗 shares_1 = [50, 100, 75, 200] shares_2 = [100, 100, 300, 500] shares_1.extend(shares_2) print shares_1 谢谢 shares_3.sort() = shares_1.extend(shares_2) 或者 shares_3 = shares_1

输出[5010075200100100100300500]

我想要的是为合并列表分配一个变量,并对列表进行排序。看到下面我的错误尝试了吗?有什么建议吗

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

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

shares_3 = shares_1 + shares_2
shares_3.sort()
答案提供了两个好方法。不过,这里有一些一般原则需要理解:首先,一般来说,当您调用更改列表的方法时,它也不会返回更改后的列表。所以

shares_3 = sorted(shares_1 + shares_2)
正如您所看到的,这些方法不返回任何内容——它们只是更改绑定到的列表。另一方面,您可以使用排序后的
sorted
,它不会改变列表,而是复制列表,对副本进行排序,然后返回副本:

>>> shares_1 = [50, 100, 75, 200]
>>> shares_2 = [100, 100, 300, 500]
>>> print shares_1.extend(shares_2)
None
>>> print shares_1.sort()
None
其次,请注意,您永远不能为函数调用赋值

>>> shares_1.extend(shares_2)
>>> shares_3 = sorted(shares_1)
>>> shares_3
[50, 75, 100, 100, 100, 100, 100, 200, 300, 300, 500, 500]
>>def foo():
...     通过
... 
>>>foo()=1
文件“”,第1行
SyntaxError:无法分配给函数调用
>>> shares_1.extend(shares_2)
>>> shares_3 = sorted(shares_1)
>>> shares_3
[50, 75, 100, 100, 100, 100, 100, 200, 300, 300, 500, 500]
>>> def foo():
...     pass
... 
>>> foo() = 1
  File "<stdin>", line 1
SyntaxError: can't assign to function call