2013-07-04 104 views
0

我有一个包含100个元素的列表。我正在尝试创建一个函数,它将创建该列表的300个副本,然后将这些副本存储到一个空白列表中。然后我需要从每个复制列表中随机选择一个索引值。因此,它可能会在第一个复制列表中选择第25个索引值,然后它可能会在下一个复制列表中选择第60个索引值。然后,该值的索引是预定义函数的参数。问题是我的复制列表没有被操纵。操作Python列表

我的代码如下:

def condition_manipulate(value): 
    list_set=[]     #this is the list in which the copied lists will go 
    for i in range(0,value): 
     new_list=initial_conditions[:] #initial_conditions is the list to be copied 
     list_set.append(new_list) 
     for i in list_set:   #My confusion is here. I need the function to choose 
      for j in i:    #A random value in each copied list that resides 
       x=random.choice(i) #In list_set and then run a predefined function on it. 
       variable=new_sum(i.index(x) 
       i[i.index(x)]=variable 
    return list_set 

#running condition_manipulate(300) should give me a list with 300 copies of a list 
#Where a random value in each list is manipulated by the function new_sum 

我已经试过几乎所有的东西。我究竟做错了什么?任何帮助将不胜感激。谢谢。

+4

什么,这里是你的最终目标?是否有理由需要300份同一份清单? – vroomfondel

+0

我们在一个小时前有同样的问题lol – Stephan

+0

为什么你不从同一个列表中选择三次? –

回答

1

尝试:

import random 

def condition_manipulate(value): 
    list_set=[] 
    for i in range(value): 
     new_list=initial_conditions[:] 
     i=random.choice(range(len(initial_conditions))) 
     new_list[i]=new_sum(new_list[i]) 
     list_set.append(new_list) 
    return list_set 
+0

非常感谢你。此代码最终工作。 我真的很感谢你的帮忙! – user2509830

1

如果你真的需要列出的副本,而不是浅拷贝,那么你需要:

import copy 

oldlist = [.....] 
newlist = copy.deepcopy(oldlist) 

否则所有副本实际上是同一个列表>>> O = [1,2,3]

>>> n = o 
>>> n.append(4) 
>>> o 
[1, 2, 3, 4] 
>>> n = copy.deepcopy(o) 
>>> n 
[1, 2, 3, 4] 
>>> n.append(5) 
>>> n 
[1, 2, 3, 4, 5] 
>>> o 
[1, 2, 3, 4] 
>>>