我需要修改我的og列表的内容到一个不同的列表w/out实际上改变我的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
您需要制作一个
list
的副本,该副本被输入到modifyList
function
。此复制不是用myList[:]
完成的,因为您不是在这里使用myList
!您正在使用另一个名为variable
的newList
的variable
,需要对其进行复制您需要记住,
function
与一个变量一起工作,该变量被传递到它中,但它的名称已经在函数定义中赋值。因此,在这里,即使您只使用modifyList(myList)
调用函数,在函数内部,您总是使用newList
,因此尝试使用myList
执行任何操作都会抛出一个错误,表示未定义这里有另一种方法,包括列表理解。在Python中,通常不必创建带有占位符的列表并逐个放置元素:
如果要就地修改原始列表,可以使用numpy和高级切片:
相关问题 更多 >
编程相关推荐