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

时间:2015-02-24 13:00:00

标签: python

我正在尝试生成一个模式,其词汇表只能由'A', 'B', 'C', 'D' or '*'组成,字符可以重复任意次,但是捕获的结果是模式必须至少有一个字母。

我尝试使用随机模块,这是我最接近我想要的:

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

理想情况下,我希望看到输出:

A***
ABAB
ABC*

等等

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

实际上你想要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
 .
 .

如果您只是想获得相同的子集,您可以使用以下列表理解,例如:

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

答案 1 :(得分:0)

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