[sum(lst[:i+1])+1 for i in range(len(lst))]
^^^^^^^^^^^^^^^^
# This element is the sum+1 of the slice starting at lst[0] and ending at i,
[sum(lst[:i+1])+1 for i in range(len(lst))]
^^^^^^^^^^^^^^^^^^^^^^^^
# Do this for one element each for every i in range(len(lst))
[sum(lst[:i+1])+1 for i in range(len(lst))]
^ ^
# And give me the results as a list.
请注意,您也可以使用相同的格式来生成表达式,但是用()而不是[]来封装它们,并且可以使用{key:value for key,value in iterable}来进行字典理解
最终列表中的每个元素都是原始列表中一个以上连续元素的总和,对吗?列表理解擅长从iterables构建列表:)
下面是我们正在做的,以及here's the docs on list comps:
请注意,您也可以使用相同的格式来生成表达式,但是用
()
而不是[]
来封装它们,并且可以使用{key:value for key,value in iterable}
来进行字典理解这可能比列表理解更容易理解:
如果模式是累积和+1,则应该这样做。使用一个基本的生成器和解决方案是相当简单和有效的。你知道吗
相关问题 更多 >
编程相关推荐