簡體   English   中英

在不修改python中的原始列表的情況下創建列表的新修改版本

[英]making a new modified version of a list without modifying the original list in python

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

您需要復制輸入到modifyList functionlist 這個副本不是用myList[:]完成的,因為你不在這里使用myList 您正在使用名為newList的另一個variable ,您需要復制該variable

您需要記住, 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和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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM