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

2024-09-24 02:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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风格且更短的方法。你知道吗


Tags: 方法in元素列表forlenrandomitem
2条回答

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

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中相应的列表中。你知道吗

相关问题 更多 >