如何应用两个变量的列表理解
我试图了解列表的理解,以便可以在正在从事更有效的项目上制定代码。我找到了一个易于理解的简单示例:
L = []
for i in range (1, 10):
if i%3 == 0:
L.append (i)
print(L)
[3,6,9]
,这是具有列表理解的代码:
L = [i for i in range (1, 10) if i%3 == 0]
print(L)
我试图将我刚刚学到的内容应用于此代码,但是我很难弄清楚如何做那。
L = []
M = []
for i in range (1, 10):
if i%3 == 0:
L.append (i)
M.append(i*2)
print(L,M)
[3,6,9] [6,12,18]
以下内容无效,但说明了我在寻找的内容:
[L,M] = [i for i in range (1, 10) if i%3 == 0, i*2 for i in range (1, 10) if i%3 == 0]
I am trying to understand list comprehention so that I can make the code on a project I'm working on more efficient. I found a simple example which is easy to understand:
L = []
for i in range (1, 10):
if i%3 == 0:
L.append (i)
print(L)
[3, 6, 9]
And this is the code with list comprehension:
L = [i for i in range (1, 10) if i%3 == 0]
print(L)
I tried to apply what I have just learned to this code but I'm having trouble figuring out how to do that.
L = []
M = []
for i in range (1, 10):
if i%3 == 0:
L.append (i)
M.append(i*2)
print(L,M)
[3, 6, 9] [6, 12, 18]
The following is not valid Python, but illustrates what I'm looking for:
[L,M] = [i for i in range (1, 10) if i%3 == 0, i*2 for i in range (1, 10) if i%3 == 0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您要查找的列表理解的语法比您想象的要简单得多:
现在是最后一个位置的位置:
l,m
。您需要的是此问题
因此,例如:
另请参见此 link 显示如何在循环和列表理解之间进行转换。
The syntax of the list comprehension that you are looking for is far simpler than you imagine:
Now for the last bit where you are after two lists:
L,M
.What you need are the answers to this question
So, for example:
Also see this link which dynamically shows how to transform between for loop and list comprehension.
您需要2个列表综合,其中之一将产生
l
和另一个m
。您几乎在那里,除了几个括号实际上,您无需将
l
和m
放入列表中 - 这可以正常工作You want 2 list comprehensions, one of which produces
L
and the otherM
. You are almost there, except for a couple of bracketsIn fact, you don't need to put
L
andM
in a list - this works just fine谢谢您的建议!他们俩都帮助我解决了我的脑海中的结,所以只能将绿色支票提供给其中一个是不公平的。
起初, mortz'代码对我来说很有意义,因为它非常接近我的“解决方案”。经过一番处理后,我也理解了Quamranas 解决方案,起初似乎更复杂。
这样写下来,紧随其后的事情有助于我理解。这对许多人来说似乎很微不足道,但是也许它可以帮助像我一样慢的人。
Thank you for your suggestions! They both helped me to resolve the knot in my head, so it's a bit unfair to have to give the green check to only one of them.
At first, Mortz' code made a lot of sense to me because it was very close to my 'solution'. After some crunching, I understood quamranas solution too, which seemed more complicated at first.
Writing it down like this and following closely what happens helped me understand. It may seem trivial to many, but maybe it helps someone who is as slow as me.