简体   繁体   English

从列表中生成随机元素,每个元素不超过一次重复

[英]Generate random element from list with no more than one repetition of one element

I am trying to generate a pattern whose vocabulary can consist of only 'A', 'B', 'C', 'D' or '*' , characters can repeat any number of times but the catch is that resulting the pattern must have at least one letter. 我正在尝试生成一个其词汇表只能由'A', 'B', 'C', 'D' or '*' ,字符可以重复任意次数,但要注意的是,导致该模式必须具有至少一个字母。

I tried with random module and this is the closest I came to what I want: 我尝试使用随机模块,这是我最想要的:

random.sample(set(vocabulary), 5)
Out[30]: ['A', 'D', '*', 'B', 'C']

Ideally I would like to see output like: 理想情况下,我希望看到如下输出:

A***
ABAB
ABC*

and so on 等等

how can I go about this? 我该怎么办?

Actually you want the product of your list element, you can use itertools.product : 实际上,您需要list元素的乘积,可以使用itertools.product

>>> from itertools import product
>>> voc=['A', 'B', 'C', 'D', '*']
>>> for pro in product(voc,repeat=5):
...    print ''.join(pro)
*AAAA
*AAAB
*AAAC
*AAAD
*AAA*
*AABA
*AABB
*AABC
 .
 .

And if you just want to get ride of equal subsets you can use the following list comprehension, for example: 而且,如果您只是想获得相等的子集,则可以使用以下列表理解,例如:

>>> voc=['C', 'D', '*']
>>> list(product(voc,repeat=3))
[('C', 'C', 'C'), ('C', 'C', 'D'), ('C', 'C', '*'), ('C', 'D', 'C'), ('C', 'D', 'D'), ('C', 'D', '*'), ('C', '*', 'C'), ('C', '*', 'D'), ('C', '*', '*'), ('D', 'C', 'C'), ('D', 'C', 'D'), ('D', 'C', '*'), ('D', 'D', 'C'), ('D', 'D', 'D'), ('D', 'D', '*'), ('D', '*', 'C'), ('D', '*', 'D'), ('D', '*', '*'), ('*', 'C', 'C'), ('*', 'C', 'D'), ('*', 'C', '*'), ('*', 'D', 'C'), ('*', 'D', 'D'), ('*', 'D', '*'), ('*', '*', 'C'), ('*', '*', 'D'), ('*', '*', '*')]
>>> list(i for i in product(voc,repeat=3)if len(set(i))>1)
[('C', 'C', 'D'), ('C', 'C', '*'), ('C', 'D', 'C'), ('C', 'D', 'D'), ('C', 'D', '*'), ('C', '*', 'C'), ('C', '*', 'D'), ('C', '*', '*'), ('D', 'C', 'C'), ('D', 'C', 'D'), ('D', 'C', '*'), ('D', 'D', 'C'), ('D', 'D', '*'), ('D', '*', 'C'), ('D', '*', 'D'), ('D', '*', '*'), ('*', 'C', 'C'), ('*', 'C', 'D'), ('*', 'C', '*'), ('*', 'D', 'C'), ('*', 'D', 'D'), ('*', 'D', '*'), ('*', '*', 'C'), ('*', '*', 'D')]
chars=['A', 'B', 'C', 'D', '*']
s=""
L = len(chars)
for i in range(0,5):
    s += chars[random.randrange(0,L)]

# now ensure that a character is present by setting a random character
s[random.randrange(0,5)] = chars[random.randrange(0,L-1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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