如需更通用的解决方案,您可以求助于Python generators。
给定任意可迭代的输入(例如:您的四个输入字符串),以下生成器将从该列表中生成无限可迭代的选择,没有两个并排的元素相同:
import random
def noncontiguous(inputs):
last = random.choice(inputs)
yield last
while True:
next = random.choice(inputs)
if next != last:
last = next
yield next
然后您可以使用列表推导式或基本的 for 循环来获取此无限序列的 16 个元素子集:
>>> gen = noncontiguous(['a', 'b', 'c', 'd'])
>>> [gen.next() for i in range(16)]
['c', 'b', 'c', 'b', 'a', 'c', 'b', 'c', 'd', 'a', 'd', 'c', 'a', 'd', 'b', 'c']
更有趣的是,你可以继续使用同一个生成器对象来创建更多不连续的元素
>>> for i in range(8):
... gen.next()
...
'b'
'c'
'd'
'c'
'b'
'd'
'a'
'c'