在python中循环一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52459681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
for loop one line in python
提问by z-one ng
When I tried to use for statement in one line like below,
当我尝试在如下一行中使用 for 语句时,
def get_cubes(x):
ls=[]
ls.append(pow(item*3, 3)) for item in range(int((x-x%3)/3)+1)
return ls
there always an error:
总是有一个错误:
File "<ipython-input-47-8c391c3d568a>", line 3
ls.append(pow(item*3, 3)) for item in range(int((x-x%3)/3)+1)
^
SyntaxError: invalid syntax
But when I write it in regular for loop method, it works well. Can anyone tell me why?
但是当我用常规的 for 循环方法编写它时,它运行良好。谁能告诉我为什么?
回答by PabloTrinidad
?Solution
?解决方案
If you strictly want a one-liner, then this is the solution:
如果您严格想要单线,那么这就是解决方案:
get_cubes = lambda x: [pow(i, 3) for i in range(0, x+1, 3)]
But since clarity and readability should always be a priority in Python, it's better to write it as a function just like @daniel did:
但由于清晰性和可读性在 Python 中始终是优先考虑的事项,因此最好像 @daniel 那样将其编写为函数:
def get_cubes(x):
return [pow(i, 3) for i in range(0, x+1, 3)]
?Output
?输出
Using a for loop to test the function you get the following results:
使用 for 循环来测试该函数,您会得到以下结果:
for i in range(20):
print(i, ':', get_cubes(i))
0 : [0]
1 : [0]
2 : [0]
3 : [0, 27]
4 : [0, 27]
5 : [0, 27]
6 : [0, 27, 216]
7 : [0, 27, 216]
8 : [0, 27, 216]
9 : [0, 27, 216, 729]
10 : [0, 27, 216, 729]
11 : [0, 27, 216, 729]
12 : [0, 27, 216, 729, 1728]
13 : [0, 27, 216, 729, 1728]
14 : [0, 27, 216, 729, 1728]
15 : [0, 27, 216, 729, 1728, 3375]
16 : [0, 27, 216, 729, 1728, 3375]
17 : [0, 27, 216, 729, 1728, 3375]
18 : [0, 27, 216, 729, 1728, 3375, 5832]
19 : [0, 27, 216, 729, 1728, 3375, 5832]
Explanation
解释
For those who asked why @daniel's code work:
对于那些问为什么@daniel 的代码有效的人:
The original code does the following:
原始代码执行以下操作:
- Given an
x
, iterate from0
to the number of times3 divides x
plus1
. - For each x, multiply it by 3 and raise it to the power of 3
- Return the list containing the results of step 2
- 给定
x
,从0
到迭代次数3 divides x
plus1
。 - 对于每个 x,乘以 3 并将其提高到 3 的幂
- 返回包含第 2 步结果的列表
Step 1was originally written as
步骤 1最初写为
range(int((x - x%3) / 3) + 1)
which subtracts the reminder of a number when divided by 3
and then divides that result by 3
before adding 1
. But the same result can be achieved by just getting the integer part of dividing x
by 3
and then adding 1
which will look something like this:
它在被3
除时减去一个数字的提醒,然后3
在添加之前将该结果除以1
。但同样的结果可以通过刚开划分的整数部分来实现x
的3
,然后加入1
,这将是这个样子:
int(x / 3) + 1
Step 2multiplies each iteration by 3
before raising it to the power of 3
but that "multiplication"can be achieved as well by using ranges (just like @daniel did) using:
第 2 步将每次迭代乘以 ,3
然后再将其提高到 的幂,3
但也可以通过使用范围(就像@daniel 所做的那样)使用以下方法实现“乘法”:
range(0, x+1, 3)
which iterate from 0
to x+1
on steps of 3
and yields the same results. I.e x
being 10
:
从0
到x+1
的步骤进行迭代3
并产生相同的结果。即x
是10
:
range(0, 10 + 1, 3) | i*3 for i in range(int(x / 3) + 1)
============================================================
0 | 0*3 = 0
3 | 1*3 = 3
6 | 2*3 = 6
9 | 3*3 = 9
For the Step 3we just need to apply pow(x, 3)
(or x ** 3
) and we can fit everything in a single line using list comprehension, then we can fit that in a lambdafunction or inside the returnstatement of a function.
对于第 3 步,我们只需要应用pow(x, 3)
(或x ** 3
) 并且我们可以使用列表推导将所有内容放入一行中,然后我们可以将其放入lambda函数或函数的return语句中。
[pow(i, 3) for i in range(0, x+1, 3)]
回答by Daniel
The correct syntax for for-loops is
for 循环的正确语法是
def get_cubes(x):
ls = []
for item in range(int((x-x%3)/3)+1):
ls.append(pow(item*3, 3))
return ls
Perhaps, you are looking for list comprehension, which is a way to generate lists, when the loop body only appends to a list:
也许,您正在寻找列表理解,这是一种生成列表的方法,当循环体仅附加到列表时:
def get_cubes(x):
ls = [(item*3) ** 3 for item in range(int((x-x%3)/3)+1)]
return ls
or in short:
或简而言之:
def get_cubes(x):
return [i ** 3 for i in range(0, x+1, 3)]
回答by Sheldore
My answer follows (modifies) your approach (code) instead of using the list comprehension but in a rectified manner. Comparing it to your code, you will figure out where the error was. I added comments #
to explain the changes
我的回答遵循(修改)您的方法(代码),而不是使用列表理解,而是以更正的方式。将它与您的代码进行比较,您将找出错误所在。我添加了注释#
来解释更改
def get_cubes(x):
ls=[] # create an empty list outside the for loop once
for item in range(int((x-x%3)/3)+1): # for loop for iterating through elements
ls.append(pow(item*3, 3)) # append one item at a time
return ls
print (get_cubes(10))
> [0, 27, 216, 729]