确定被更改的随机列表的长度

Determining length of a random list being altered

我有一个在列表中随机访问的列表,我正在向其中添加一个元素。 (请注意,元素必须随机插入到列表中,即我不想在末尾或开始时插入) 例如:

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 和更短的方法。

你可以在函数中分解每个操作:

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 中的相应列表中。