Python 确定被更改的随机列表的长度
我在一个列表中随机访问了一个列表,并向其中添加了一个元素。(请注意,必须在列表中随机插入元素,即我不想在末尾或开头插入) 例如:Python 确定被更改的随机列表的长度,python,python-3.x,list,random,variable-assignment,Python,Python 3.x,List,Random,Variable Assignment,我在一个列表中随机访问了一个列表,并向其中添加了一个元素。(请注意,必须在列表中随机插入元素,即我不想在末尾或开头插入) 例如: myList = [[0, 1, 4, 7],[0, 3, 2, 7]] toinsert = [5, 6] for item in toinsert: random.choice(myList).insert(random.randint(1,len(`the list that got chosen`)-2), item) 我试过使用 choiceli
myList = [[0, 1, 4, 7],[0, 3, 2, 7]]
toinsert = [5, 6]
for item in toinsert:
random.choice(myList).insert(random.randint(1,len(`the list that got chosen`)-2), item)
我试过使用
choicelist = random.choice(myList)
choicelist.insert(randint(1,len(choicelist)))
但考虑到这是一个随机列表,我不知道如何将其放回原来的列表中
我知道我可以为myList随机选择一个索引,并使用该方法,但我一直在寻找一种更为简捷的方法。你可以在函数中分解每个操作:
import random
def insert_at_random_place(elt, seq):
insert_index = random.randrange(len(seq))
seq.insert(insert_index, elt) # the sequence is mutated, there is no need to return it
def insert_elements(elements, seq_of_seq):
chosen_seq = random.choice(seq_of_seq)
for elt in elements:
insert_at_random_place(elt, chosen_seq)
# the sequence is mutated, there is no need to return it
myList = [[0, 1, 4, 7],[0, 3, 2, 7]]
toinsert = [5, 6]
insert_elements(toinsert, myList)
您无需执行任何操作即可将对
choicelist
的更改反映回原始列表myList
choicelist = random.choice(myList)
在上面的语句中,
choicelist
引用了myList
中的一些随机列表,即choicelist
不是由random.choice
创建的新列表。因此,您在choicelist
中所做的任何更改都将反映在myList
中的相应列表中,它仍然存在。您没有删除它或任何东西,因此不需要做任何事情来将其放回。choicelist赋值不只是创建一个单独的(不相关的)变量吗?它生成一个新变量,但不是一个新列表。谢谢,我没有意识到它创建了一个引用而不是一个新变量。有没有办法确定何时会发生这种情况(当分配变量时会创建一个新值而不是引用某个对象)?@a.Schutz:分配变量永远不会生成一个新对象。赋值将新对象分配给变量的情况是右手边创建新对象的情况;赋值本身从不创建对象。
choicelist = random.choice(myList)