[英]making a new modified version of a list without modifying the original list in python
i need to modify the contents of my og list into a different list w/out actually changing my og list. 我需要将我的og列表的内容修改为一个不同的列表,而不是实际更改我的og列表。
def createList(numbers):
my_List= [0] * numbers
for q in range(0, len(my_List)):
myList[q]= randint (1, 21)
q=q+1
return my_List
def modifyList(newList):
for i in range(0, len(newList)):
if i % 2 == 0:
newList[i]= newList[i] / 2
else:
newList[i]= newList[i] * 2
return newList
def main():
my_List= createList(10)
print my_List
newList= modifyList(my_List)
print my_List
print newList
You need to make a copy of the list
that is inputted to the modifyList
function
. 您需要复制输入到modifyList
function
的list
。 This copy isn't done with myList[:]
as you are not working with myList
here! 这个副本不是用myList[:]
完成的,因为你不在这里使用myList
! You are working with a different variable
called newList
which you need to make a copy of. 您正在使用名为newList
的另一个variable
,您需要复制该variable
。
You need to remember that a function
works with a variable that is passed into it but under the name it has been assigned in the function definition. 您需要记住, function
使用传递给它的变量,但是在函数定义中已经分配了它的名称。 So here, even though you only call the function with modifyList(myList)
, inside the function, you are always working with newList
so trying to do anything with myList
here will throw an error saying its undefined. 所以在这里,即使您只使用modifyList(myList)
调用函数,在函数内部,您始终使用newList
因此尝试使用myList
执行任何操作都将引发错误,说明其未定义。
def modifyList(newList):
newList = newList[:]
for j in range(0, len(newList)):
if j % 2 == 0:
newList[j]= newList[j] / 2
else:
newList[j]= newList[j] * 2
return newList
Here's an alternate way, with list comprehensions. 这是一种替代方式,具有列表推导。 In Python, you usually don't have to create a list with placeholders and put the elements one by one: 在Python中,您通常不必创建包含占位符的列表并逐个放置元素:
>>> from random import randint
>>> my_list = [randint(1, 20) for _ in range(10)]
>>> my_list
[1, 20, 2, 4, 8, 12, 16, 7, 4, 14]
>>> [x * 2 if i % 2 else x / 2 for i, x in enumerate(my_list)]
[0.5, 40, 1.0, 8, 4.0, 24, 8.0, 14, 2.0, 28]
If you want to modify the original list in place, you could use numpy and advanced slicing: 如果要修改原始列表,可以使用numpy和advanced切片:
>>> import numpy as np
>>> a = np.array([11, 13, 21, 12, 18, 2, 21, 1, 5, 9])
>>> a[::2] = a[::2] / 2
>>> a[1::2] = a[1::2] * 2
>>> a
array([ 5, 26, 10, 24, 9, 4, 10, 2, 2, 18])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.