2

我忘记了 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最后没有工作。那么如何在列表理解中进行等式约束呢?

4

2 回答 2

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']
于 2013-07-31T13:50:47.907 回答
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']

于 2018-06-03T12:28:22.560 回答