![](/img/trans.png)
[英]Append multiple values in dictionary but avoid repeated elements in the value of the dictionary in python
[英]Python (repeated values with append)
我有以下公式Q = [(2 * C * D)/ H]的平方根我想輸入100,150,180,所以我想要的輸出是18,22,24
所以我的代碼是
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)
當我輸入方程式(100,150,180)時,為什么輸出如下?
[18, 12, 24]
[18, 12, 24, 18, 12, 24]
[18, 12, 24, 18, 12, 24, 18, 12, 24]
我如何更改代碼,所以我只能
[18, 12, 24]
僅在列表理解中循環使用值以應用相同的公式,也不打印結果,僅返回結果(並在需要時在調用方中打印):
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))
結果:
[18, 22, 24]
(這節省了這種循環/在哪里定義返回值錯誤和大量復制/粘貼)
帶有可變參數的變體(相同的調用語法,因為所有參數得到相同的處理,因此節省了參數打包和拆包):
def equation(*args):
return [int(math.sqrt(2*c*x/h)) for x in args]
為什么要使用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)
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)
equation(100, 150, 180)
無需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)
在我看來,這就是您追求的目標:
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))
輸出:
[18, 22, 24]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.