列表理解循环Python [英] List comprehension for loops Python

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

问题描述

我使用了很多N维数组,不得不编写这样的缩进代码会很痛苦,而且我知道有些代码可以用列表推导和内联语句替换.例如:

I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:

for x in (0,1,2,3):
    for y in (0,1,2,3):
        if x < y:
            print (x, y, x*y)

可以替换为:

print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]

但是我该如何更改操作而不是打印来进行其他操作:

But how could I change the action instead of print to do something else like:

total = x+y

所以我想做的事情是这样的:

So what I want to do is something like:

[(total+=x+y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]

但是这不起作用

是否有一个聪明的方法来做到这一点,而不是:

Is there a smart way to do this rather than:

for x in (0,1,2,3):
        for y in (0,1,2,3):
            if x < y:
                total+=x+y

推荐答案

sum在这里工作:

total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)

这篇关于列表理解循环Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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