gpt4 book ai didi

Python 列表理解与求和

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:25 26 4
gpt4 key购买 nike

我有一些看起来像这样的 python 代码:

mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1,3):
nwalls = [sum(nwalls[k] for k in mat[j]) for j in range(5)]
# nwalls = [1, 2, 2, 1, 2]

如果不使用列表理解来让我理解,我一辈子都无法将其展开为语法。请协助。

最佳答案

直接翻译就是

mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1, 3):
_nwalls = []
for j in range(5):
tot = 0 # - sum
for k in mat[j]: # /
tot += nwalls[k] # /
_nwalls.append(tot)
nwalls = _nwalls

(nwalls[k] for k in mat[j]) 它自己是一个生成器,在 python repl 中,你可以检查它:

>>> y = (x for x in range(10))
>>> type(y)
<class 'generator'>

sum可以采用生成器,如sum( (x for x in range(10)) ),以及PEP289

if a function call has a single positional argument, it can be a generator expression without extra parentheses, but in all other cases you have to parenthesize it.

所以它看起来像 sum(x for x in range(10))

关于Python 列表理解与求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38016898/

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