[英]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. random.randrange(n)
返回一个 integer 在0
到n-1
的范围内。lst
100 times.列表推导从lst
100 次中重复添加一个随机元素。100
to whatever number of elements you wish to obtain.将100
更改为您希望获得的任何数量的元素。One way is to use random.sample()
:一种方法是使用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.每次调用时只需将k
设置为 1。 This gives you a list of length 1, randomly selected from the source list.这为您提供了一个长度为 1 的列表,从源列表中随机选择。
To generate a large random list, repeatedly call random.sample()
in a list comprehension , eg 150 times.要生成一个大的随机列表,请在列表理解中重复调用random.sample()
,例如 150 次。 (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). (当然,您还必须从random.sample()
索引结果列表,以便仅检索值而不是长度为 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', ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.