具有不同语句的列表理解示例 [英] List comprehension example with different statements

查看:45
本文介绍了具有不同语句的列表理解示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有下一个循环

a = 0
b = [1,2,3]

for x in b:
    print a + x
    a = x

是否有可能在列表理解中覆盖它?我的第一次尝试失败了:

is it possible to overwrite it in the list comprehension? My first attempt is fail:

a = 0
b = [1,2,3]
[[print a+x, a=x] for x in b]

    [[print a+x, a=x] for x in b]
          ^
SyntaxError: invalid syntax

推荐答案

有很多方法可以将其写为列表理解,但实际上不应该这样做.理解是面向表达式的编程,循环是副作用.

There are ways to write this as a list comprehension, but you really shouldn't. Comprehensions are for expression-oriented programming, loops are for side-effects.

这篇关于具有不同语句的列表理解示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆