Python中列表补全中的多个语句? [英] Multiple statements in list compherensions in Python?
问题描述
是否可能有类似的东西:
Is it possible to have something like:
list1 = ...
currentValue = 0
list2 = [currentValue += i, i for i in list1]
我尝试过但是没用吗?编写这些的正确语法是什么?
I tried that but didn't work? What's the proper syntax to write those?
打印语句就是一个例子.实际上,我正在循环外增加一个值.
the print statement was an example. Actually I am incrementing a value outside the loop.
推荐答案
声明不能进入Python表达式内部;这是故意从语言中设计出来的复杂功能.对于此问题,请尝试使用 did 使其成为语言(生成器)的一种复杂功能.观看:
Statements cannot go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that did make it into the language: generators. Watch:
def total_and_item(sequence):
total = 0
for i in sequence:
total += i
yield (total, i)
list2 = list(total_and_item(list1))
生成器将到目前为止所见项目的运行记录保持一致,并将其作为每个项目的前缀,就像您的示例尝试执行的那样.当然,一个简单的循环可能会更简单,它在顶部创建一个空列表,并且只需多次调用append()即可! :-)
The generator keeps a running tally of the items seen so far, and prefixes it to each item, just like it looks like you example tries to do. Of course, a straightforward loop might be even simpler, that creates an empty list at the top and just calls append() a lot! :-)
这篇关于Python中列表补全中的多个语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!