Python列表理解中的平等性

时间:2013-07-31 13:49:18

标签: python list-comprehension

我已经忘记了Python的列表理解中的平等性

[str(a)+str(b)+str(c) for a in range(3) for b in range(3) for c in range(3)]
['000', '001', '002', '010', '011', '012', '020', '021', '022', '100', '101', '102', '110', '111', '112', '120', '121', '122', '200', '201', '202', '210', '211', '212', '220', '221', '222']

我想限制a!= b和b!= c。最后for a!=b for b!=c没有用。那么如何在列表理解中使用等式约束呢?

2 个答案:

答案 0 :(得分:6)

这样的事情:

["{}{}{}".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']

答案 1 :(得分:2)

对于这类问题,iterools非常方便。 如果您希望所有项目都是唯一的,那么您正在考虑排列:

import itertools
[''.join(p) for p in itertools.permutations('012')]

['012','021','102','120','201','210']

如果您希望相邻的项目不同:

[''.join(p) for p in itertools.product('012', repeat=3) if all(p[i] != p[i+1] for i in range(len(p) - 1))]

['010','012','020','021','101','102','120','121','201','202','210','212 “]