将嵌套的Python循环转换为列表推导 [英] Transforming nested Python loops into list comprehensions
本文介绍了将嵌套的Python循环转换为列表推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经开始处理一些Euler项目的问题,并且已经解决了编号4 和一个简单的蛮力解决方案:
I've started working on some Project Euler problems, and have solved number 4 with a simple brute force solution:
def mprods(a,b):
c = range(a,b)
f = []
for d in c:
for e in c:
f.append(d*e)
return f
max([z for z in mprods(100,1000) if str(z)==(''.join([str(z)[-i] for i in range(1,len(str(z))+1)]))])
解决后,我试图使其尽可能紧凑,并提出了可怕的底线!
After solving, I tried to make it as compact as possible, and came up with that horrible bottom line!
不要遗漏一些东西,我正在尝试将mprods
函数压缩为一个列表理解.到目前为止,我已经提出了以下尝试:
Not to leave something half-done, I am trying to condense the mprods
function into a list comprehension. So far, I've come up with these attempts:
-
[d*e for d,e in (range(a,b), range(a,b))]
显然完全走在错误的轨道上. :-) -
[d*e for x in [e for e in range(1,5)] for d in range(1,5)]
这给了我[4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16]
,在我期望的地方[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]
或类似版本.
[d*e for d,e in (range(a,b), range(a,b))]
Obviously completely on the wrong track. :-)[d*e for x in [e for e in range(1,5)] for d in range(1,5)]
This gives me[4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16]
, where I expect[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]
or similar.
有没有Pythonistas可以帮助您? :)
Any Pythonistas out there that can help? :)
推荐答案
c = range(a, b)
print [d * e for d in c for e in c]
这篇关于将嵌套的Python循环转换为列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文