Equality in Python's list-comprehension -


i have forgotten equalities in python's list-comprehension

[str(a)+str(b)+str(c) in range(3) b in range(3) 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'] 

where want make restriction a!=b , b!=c. for a!=b b!=c @ end did not work. how have equality constraint in list-comprehension?

something this:

["{}{}{}".format(a,b,c) in range(3) b in range(3)                                                c in range(3) if a!=b , b!=c] 

or better use itertools.product:

>>> itertools import product >>> ["{}{}{}".format(a,b,c)  a, b, c in product(range(3), repeat=3)                                                                if a!=b , b!=c] ['010', '012', '020', '021', '101', '102', '120', '121', '201', '202', '210', '212'] 

update :

>>> itertools import product, izip, tee def check(lis):     it1, it2 = tee(lis)     next(it2)     return all(x != y x,y in izip(it1, it2)) ...   >>> n = 3 >>> [("{}"*n).format(*p)  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)  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'] 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -