我在一个列表中随机访问了一个列表,并在其中添加了一个元素。(请注意,元素必须随机插入到列表中,即我不想在末尾或开头插入) 例如:
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
随机选择一个索引并使用该方法,但我希望能找到一种更具Pythonic风格且更短的方法。你知道吗
您可以在函数中分解每个操作:
您不需要做任何事情就可以使对
choicelist
的更改反映回原始列表myList
。你知道吗在上面的语句中,
choicelist
是对myList
内某个随机列表的引用,即choicelist
不是由random.choice
创建的新列表。因此,您在choicelist
中所做的任何更改都将反映在myList
中相应的列表中。你知道吗相关问题 更多 >
编程相关推荐