Python | How to append elements to a list randomly

2020-06-12 06:02发布

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']

But I want it to add elements randomly and out put something like this: ['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.

标签: python
4条回答
够拽才男人
2楼-- · 2020-06-12 06:23
from random import choice

n=10
seq=['a','b','c','d']
rstr=[choice(seq) for i in range(n)]
查看更多
爷的心禁止访问
3楼-- · 2020-06-12 06:42

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']
查看更多
孤傲高冷的网名
4楼-- · 2020-06-12 06:46

random.shuffle is 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.

查看更多
别忘想泡老子
5楼-- · 2020-06-12 06:47

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:

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))]
查看更多
登录 后发表回答