Python列表理解中的平等性

问题描述 投票:2回答: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最后没有奏效。那么如何在列表理解中使用等式约束呢?

python list-comprehension
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']

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

© www.soinside.com 2019 - 2024. All rights reserved.