Python 循环的列表理解
我使用了很多 N 维数组,编写这样的缩进代码很痛苦,而且我知道有些代码可以用列表理解和内联语句替换。例如:
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]
但是我如何更改操作而不是打印来执行其他操作,例如:
total = x+y
所以我想做的是:
[(total+=x+y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
但是这不起作用 有没有
一种聪明的方法可以做到这一点而不是:
for x in (0,1,2,3):
for y in (0,1,2,3):
if x < y:
total+=x+y
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)
can be replaced with:
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]
However this doesn't work
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 numpy。这使您可以使用像向量一样相加的数组:
通过修改后的问题,还添加对
sum
的调用Use numpy. This lets you use arrays that add up like vectors:
With the modified question, add a call to
sum
as well归约函数直接将集合项减少为单个项。您可以在此处阅读有关它们的更多信息,但这应该对您有用:
或者
Reduce function directly reduces collective items to single item. You can read more about them here, but this should work for you:
or
另一种可能性是:
通过这种方式,您可以迭代在列表理解中使用的任何内容,而无需实际创建理解列表(如果您明白我的意思;)如果理解列表很大,可能太大以至于饱和甚至不饱和放在内存里,蛮方便的
Another possibility is:
In this way you can iterate over anything you'd use in a list comprehension without actually creating the comprehended list (if you get my meaning ;) If comprehended list is big, maybe so big it saturates or even doesn't fit in memory, that's quite handy..
sum
在这里工作:sum
works here:作为编写 N 层深度循环的替代方法,您可以使用
itertools.product ()
:这自然延伸到 N 维。
As an alternative to writing loops N levels deep, you could use
itertools.product()
:This extends naturally to N dimensions.