python - 如何以pythonic方式查看for循环中的for循环
问题描述
我从 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
andif
放在一个新行上):
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))
对于问题中的示例,result
列表理解内部指的是 的旧值result
,因此在创建新值时需要保留该值result
:
result = [[]]
for pool in pools:
old_result = result # remember the old result
result = [] # build the new result with this variable
for x in old_result:
for y in pool:
result.append(x + [y])
result
或者,您可以在不同的变量中构建新变量并将其设置result
为:
result = [[]]
for pool in pools:
new_result = [] # build the new result with this variable
for x in result:
for y in pool:
new_result.append(x + [y])
result = new_result # update our current result
这里还有另一个例子。
推荐阅读
- android - 是什么让 singleTask 活动有 2 个实例?
- android - recyclerview addOnScrollListener 未在 recyclerview 位于滚动视图内时调用
- r - 根据唯一标识符聚合行
- c# - 我正在尝试在 Visual Studio 中运行所有测试,但是当我运行测试时,第一个会通过,但其他所有测试都会失败
- html - hreview 结合 schema 的 review itemtype
- c# - .net核心无法从python脚本打开文件
- ruby-on-rails - 使用 cancan 限制对 admin/* 站点的访问
- typescript - TypeScript - 覆盖 vscode 中的 linter 错误
- java - Ontouchlistener 防止滚动
- webpack - Webpack 问题(通过 O'Reilly React 书)