[英]create new list without changing the original list
I have a list : 我有一个清单:
L=[2,0,4,5]
and I want to create a new list without changing L itself: 我想创建一个新的列表而不改变L本身:
K= [0,2,4,5]
but when I try: 但是当我尝试:
K=L.sort()
print(K)
it prints nothing, and if I try: 它没有打印,如果我尝试:
print(L)
it comes out : [0,2,4,5] 它出来了:[0,2,4,5]
why K is not =[0,2,4,5]? 为什么K不是= [0,2,4,5]? and how can I make a new list [0,2,4,5] and don't change L? 如何创建新列表[0,2,4,5]并且不更改L?
The following will make a sorted copy of L
and assign it to K
: 以下将生成L
的排序副本并将其分配给K
:
K = sorted(L)
sorted()
is a builtin function. sorted()
是一个内置函数。
The reason K = L.sort()
doesn't work is that sort()
sorts the list in place , and returns None
. K = L.sort()
不起作用的原因是sort()
对列表进行排序,并返回None
。 This is why L
ends up being modified and K
ends up being None
. 这就是L
最终被修改而K
最终为None
。
Here is how you could use sort()
: 以下是使用sort()
:
K = L[:] # make a copy
K.sort()
你需要使用内置函数sorted
: sorted(L)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.