简体   繁体   English

创建新列表而不更改原始列表

[英]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()

你需要使用内置函数sortedsorted(L)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过将字符串添加到现有列表而不更改 python 中的现有列表来创建新列表? - How to create a new list by adding a string to existing list without changing the existing list in python? 在不修改python中的原始列表的情况下创建列表的新修改版本 - making a new modified version of a list without modifying the original list in python 如何在不更改原始字典的情况下将值分配给重复字典中的列表 - how to assign values to a list in duplicated dictionary without changing the original dictionary 创建一个字符串更改一个字符的新列表 - Create a new list with a string changing one character 更改函数内部的原始列表 - changing the original list inside function Python:如何在不反转原始字典的情况下反转新字典中的列表 - Python: How to reverse a list in a new dictionary without reversing the original 是否可以忽略列表的最后一个元素而不必创建另一个列表,也无需修改原始列表? - Is it possible to ignore the last element of a list without having to create another list and without modifing the original list? 是否在不更改列表原始顺序的情况下删除列表中其他字符串的子字符串的字符串? - Remove a string that is a substring of other string in the list WITHOUT changing original order of the list? 如何在不更改原始列表的情况下使变量等于删除了项目的列表? - How to make a variable equal to a list with items removed, without changing original list? 如何在不更改原始列表的情况下为每个等于零的列表元素打印空白空间? - How can I print empty space for every list element which is equal to zero without changing the original list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM