python 蟒蛇| 如何将元素随机附加到列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2475518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:44:37  来源:igfitidea点击:

Python | How to append elements to a list randomly

python

提问by Switch

Is there a way to append elements to a list randomly, built in function

有没有办法将元素随机附加到列表中,内置函数

ex:

前任:

def random_append():
     lst = ['a']
     lst.append('b')
     lst.append('c')
     lst.append('d')
     lst.append('e')
     return print lst

this will out put ['a', 'b', 'c', 'd', 'e']

这将输出 ['a', 'b', 'c', 'd', 'e']

But I want it to add elements randomly and out put something like this: ['b', 'd', 'b', 'e', 'c']

但我希望它随机添加元素并输出如下内容: ['b', 'd', 'b', 'e', 'c']

And yes there's a function random.shuffle() but it shuffles a list at once which I don't require, I just want to perform random inserts only.

是的,有一个函数 random.shuffle() 但它一次洗牌一个我不需要的列表,我只想执行随机插入。

采纳答案by Ants Aasma

If you need to perform single insert in a random position then the already given trivial exapmle works:

如果您需要在随机位置执行单个插入,那么已经给出的简单示例可以工作:

from random import randrange, sample

def random_insert(lst, item):
    lst.insert(randrange(len(lst)+1), item)

However if you need to insert k items to a list of length n then using the previously given function is O(n*k + k**2) complexity. However inserting multiple items can be done in linear time O(n+k) if you calculate the target positions ahead of time and rewrite the input list in one go:

但是,如果您需要将 k 个项目插入到长度为 n 的列表中,那么使用前面给出的函数的复杂度为 O(n*k + k**2)。但是,如果您提前计算目标位置并一次性重写输入列表,则可以在线性时间 O(n+k) 内插入多个项目:

def random_insert_seq(lst, seq):
    insert_locations = sample(xrange(len(lst) + len(seq)), len(seq))
    inserts = dict(zip(insert_locations, seq))
    input = iter(lst)
    lst[:] = [inserts[pos] if pos in inserts else next(input)
        for pos in xrange(len(lst) + len(seq))]

回答by John La Rooy

If there is supposed to be exactly one of each item

如果每个项目应该只有一个

>>> from random import randint
>>> a=[]
>>> for x in "abcde":
...  a.insert(randint(0,len(a)),x)
... 
>>> a
['b', 'a', 'd', 'c', 'e']

If you are allowing duplicates (as the output indicates)

如果您允许重复(如输出所示)

>>> from random import choice
>>> a=[choice("abcde") for x in range(5)]
>>> a
['a', 'b', 'd', 'b', 'a']

回答by Mike Graham

random.shuffleis probably the best tool for the job. It is simple, obvious, and well-named—it's probably more readable than the other suggestions you will get. Additionally, using it is O(n), but using insert(an O(n) operation) n times is quadratic.

random.shuffle可能是这项工作的最佳工具。它简单、明显且命名良好——它可能比您将获得的其他建议更具可读性。此外,使用它是 O(n),但使用insert(一个 O(n) 操作)n 次是二次的。

回答by Luka Rahne

from random import choice

n=10
seq=['a','b','c','d']
rstr=[choice(seq) for i in range(n)]