在python中创建列表的新修改版本而不修改原始列表

2024-09-30 14:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要修改我的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

Tags: in列表forlenreturnmydefrange
2条回答

您需要制作一个list的副本,该副本被输入到modifyListfunction。此复制不是用myList[:]完成的,因为您不是在这里使用myList!您正在使用另一个名为variablenewListvariable,需要对其进行复制

您需要记住,function与一个变量一起工作,该变量被传递到它中,但它的名称已经在函数定义中赋值。因此,在这里,即使您只使用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

这里有另一种方法,包括列表理解。在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]

如果要就地修改原始列表,可以使用numpy和高级切片:

>>> 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])

相关问题 更多 >