gpt4 book ai didi

python - Python 列表理解中的平等

转载 作者:行者123 更新时间:2023-11-28 20:24:04 26 4
gpt4 key购买 nike

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

最佳答案

像这样:

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

关于python - Python 列表理解中的平等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17972266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com