我从itertools.product中找到此代码,以找到列表的唯一组合
args = [["a","b"], ["a", "c", "d"], ["h"]]
pools = [tuple(pool) for pool in args]
for pool in pools:
result = [x + [y] for x in result for y in pool]
给出:
print(result)
[['a', 'a', 'h'], ['a', 'c', 'h'], ['a', 'd', 'h'], ['b', 'a', 'h'], ['b', 'c', 'h'], ['b', 'd', 'h']]
现在,我想知道是否存在一种使用for循环以“正常”方式编写此代码的方法?我设法用if语句将其重写为一个for循环,如下所示:
[s for s in p if s != 'a']
等于:
s = []
for x in p:
if x != 1:
s.append(x)
但是我没有设法在for循环中为for循环执行此操作...对此我还很陌生,所以我猜测必须有某种方法可以执行此操作,但我看不到怎么样。有人怎么做吗?
例如,我认为您可以继续发展趋势:
[(x,y) for x in [0,1,2,3,4,5] if x < 3 for y in [0,1,2,3,4,5] if 2 < y if x + y == 4]
等效于(通过将每个for
和if
都放在换行符上:]
s = []
for x in [0,1,2,3,4,5]:
if x < 3:
for y in [0,1,2,3,4,5]:
if 2 < y:
if x + y == 4:
s.append((x,y))
还有另一个例子here。