将两个列表合并为新列表并排序
shares_1 = [50, 100, 75, 200]
shares_2 = [100, 100, 300, 500]
shares_1.extend(shares_2)
print shares_1
输出结果是 [50, 100, 75, 200, 100, 100, 300, 500]
我想把合并后的列表赋值给一个变量,并对这个列表进行排序。下面是我错误的尝试,有什么建议吗?
shares_3.sort() = shares_1.extend(shares_2)
谢谢!
3 个回答
5
shares_3 = shares_1 + shares_2
shares_3.sort()
shares_1.extend(shares_2)
shares_1.sort()
另外,
9
shares_3 = sorted(shares_1 + shares_2)
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
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
正如你所看到的,这些方法不会返回任何东西——它们只是改变了它们所绑定的列表。另一方面,你可以使用 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]
其次,要注意你永远不能对一个函数调用进行赋值。
>>> def foo():
... pass
...
>>> foo() = 1
File "<stdin>", line 1
SyntaxError: can't assign to function call