[英]Python (repeated values with append)
I have the following formula Q = Square root of [(2 * C * D)/H] And I would like to input 100,150,180 so the output i want is 18,22,24 我有以下公式Q = [(2 * C * D)/ H]的平方根我想输入100,150,180,所以我想要的输出是18,22,24
so my code is 所以我的代码是
import math
c=50
h=30
value=[]
def equation(a1,b1,c1):
for i in (a1,b1,c1):
value.append(int(math.sqrt(2*c*a1/h)))
value.append(int(math.sqrt(2*c*b1/h)))
value.append(int(math.sqrt(2*c*c1/h)))
print (value)
when I input equation(100,150,180), why is the output following? 当我输入方程式(100,150,180)时,为什么输出如下?
[18, 12, 24]
[18, 12, 24, 18, 12, 24]
[18, 12, 24, 18, 12, 24, 18, 12, 24]
How do i change the code so i get only 我如何更改代码,所以我只能
[18, 12, 24]
loop on values only to apply the same formula, in a list comprehension, also don't print the result, just return it (and print it in the caller if needed): 仅在列表理解中循环使用值以应用相同的公式,也不打印结果,仅返回结果(并在需要时在调用方中打印):
import math
c=50
h=30
def equation(a1,b1,c1):
return [int(math.sqrt(2*c*x/h)) for x in (a1,b1,c1)]
print(equation(100,150,180))
result: 结果:
[18, 22, 24]
(this saves this kind of loop/where do I define my return value errors and a lot of copy/paste) (这节省了这种循环/在哪里定义返回值错误和大量复制/粘贴)
Variant with variable arguments (same calling syntax, saves argument packing & unpacking since all arguments get the same treatment): 带有可变参数的变体(相同的调用语法,因为所有参数得到相同的处理,因此节省了参数打包和拆包):
def equation(*args):
return [int(math.sqrt(2*c*x/h)) for x in args]
Why do you use the for
loop? 为什么要使用
for
循环?
import math
c=50
h=30
def equation(a1,b1,c1):
value=[]
value.append(int(math.sqrt(2*c*a1/h)))
value.append(int(math.sqrt(2*c*b1/h)))
value.append(int(math.sqrt(2*c*c1/h)))
print (value)
The for loop seems a little bit unnecessary here. for循环在这里似乎没有必要。 If you simply want the function to return a list of the three numbers, you can use:
如果仅希望函数返回三个数字的列表,则可以使用:
import math
c = 50
h = 30
def equation(a1, b1, c1):
value = []
value.append(int(math.sqrt(2 * c * a1 / h)))
value.append(int(math.sqrt(2 * c * b1 / h)))
value.append(int(math.sqrt(2 * c * c1 / h)))
print(value)
equation(100, 150, 180)
No need of for
loop. 无需
for
循环。
import math
c=50
h=30
value=[]
def equation(a1,b1,c1):
value.append(int(math.sqrt(2*c*a1/h)))
value.append(int(math.sqrt(2*c*b1/h)))
value.append(int(math.sqrt(2*c*c1/h)))
print (value)
It seems to me that this is what you were after: 在我看来,这就是您追求的目标:
import math
c = 50
h = 30
def equation(values):
return [int(math.sqrt(2*c*i/h)) for i in values]
input = [100, 150, 180]
print(equation(input))
Output: 输出:
[18, 22, 24]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.