简体   繁体   中英

Create random list of given length from a list of strings in python

I have a list of strings:

lst = ["orange", "yellow", "green"]    

and I want to randomly repeat the values of strings for a given length.

This is my code:

import itertools
lst = ["orange", "yellow", "green"]
list(itertools.chain.from_iterable(itertools.repeat(x, 2) for x in lst))

This implementation repeats but not randomly and also it repeats equally, whereas it should be random as well with the given length.

You can use a list comprehension:

import random
lst = ["orange", "yellow", "green"]
[lst[random.randrange(len(lst))] for i in range(100)]

Explanation:

  • random.randrange(n) returns an integer in the range 0 to n-1 included.
  • the list comprehension repeatedly adds a random element from lst 100 times.
  • change 100 to whatever number of elements you wish to obtain.

One way is to use random.sample() :

Return ak length list of unique elements chosen from the population sequence or set.

Simply set k to be 1 each time you call it. This gives you a list of length 1, randomly selected from the source list.

To generate a large random list, repeatedly call random.sample() in a list comprehension , eg 150 times. (Of course, you have to also index the resulting list from random.sample() so that you retrieve just the value rather than a list of length 1).

For example:

import random
lst = ["orange", "yellow", "green"]
print([random.sample(lst, k=1)[0] for i in range(150)])
# Output
# ['green', 'orange', 'green', 'yellow', 'green', ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM