我想在这里将列表复制到新列表中,但我的代码无效:
l = list(range(0,101,2))
n = []
def change(l):
for i in range (len(l)):
k = l.copy()
n[k] = l[:]
print (l)
print (n)
我想将l列表复制到n列表中,但是不起作用。 预先感谢您的帮助。
答案 0 :(得分:1)
>>>l = range(0,101,2)
>>>n = [x for x in l]
答案 1 :(得分:0)
您可以使用https://docs.python.org/2/library/copy.html
import copy
n = copy.copy(l)
为避免n = l
出现以下问题:
l = list(range(0,21,2))
n = []
n = l
l.append(1000)
print (n) #=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1000]
答案 2 :(得分:0)
n = l[:]
是不使用任何模块复制列表的一种方法:
l = list(range(0,101,2)) # get list of even values from 0 to 100
n = l[:] # copy data from l to n
print (l) # check data of l
print(n) # check data of n
l.pop() # remove last element from l
print(l) # It prints only 0 to 98
print(n) # It prints from 0 to 100 (can you see here, changing l doesnot impact n)
现在,如果直接使用n = l
,则l
中的任何更改都会更改n
中的值,请检查以下代码:
l = list(range(0,101,2))
n=l
print (l) # check data of l
print(n) # check data of n
l.pop() # remove last element from l
print(l) # It prints from 0 to 98
print(n) # It prints from 0 to 98