像这样的东西:
["{}{}{}".format(a,b,c) for a in range(3) for b in range(3)
for c in range(3) if a!=b and b!=c]
或更好地使用itertools.product
:
>>> from itertools import product
>>> ["{}{}{}".format(a,b,c) for a, b, c in product(range(3), repeat=3)
if a!=b and b!=c]
['010', '012', '020', '021', '101', '102', '120', '121', '201', '202', '210', '212']
更新 :
>>> from itertools import product, izip, tee
def check(lis):
it1, it2 = tee(lis)
next(it2)
return all(x != y for x,y in izip(it1, it2))
...
>>> n = 3
>>> [("{}"*n).format(*p) for p in product(range(3), repeat=n) if check(p)]
['010', '012', '020', '021', '101', '102', '120', '121', '201', '202', '210', '212']
>>> n = 4
>>> [("{}"*n).format(*p) for p in product(range(3), repeat=n) if check(p)]
['0101', '0102', '0120', '0121', '0201', '0202', '0210', '0212', '1010', '1012', '1020', '1021', '1201', '1202', '1210', '1212', '2010', '2012', '2020', '2021', '2101', '2102', '2120', '2121']