我是 Python 新手,正在嘗試學習函式的使用。我有一些數字要分類為低和高。并希望通過呼叫函式對它們進行排序。你會怎么做?下面的代碼:)
rsi_list = ([14, 88, 56, 74, 25, 22, 41, 55, 31, 98, 44, 56, 24, 43, 87, 15, 91, 71, 14, 16, 33, 38, 4, 6, 3, 78])
def sort_rsi_low(x):
low_rsi = []
for n in rsi_list:
if n < 50:
low_rsi.append(n)
return low_rsi
print(sort_rsi_low(rsi_list))
def sort_rsi_high(x):
high_rsi = []
for n in rsi_list:
if n > 50:
high_rsi.append(n)
return high_rsi
print(sort_rsi_high(rsi_list))
uj5u.com熱心網友回復:
我不太明白這個用例,但我認為這可以使用單個函式來解決:
def sort_low_high(x):
low_rsi, high_rsi = [], []
for n in x:
if n < 50:
low_rsi.append(n)
else:
high_rsi.append(n)
return low_rsi, high_rsi
然后,呼叫函式并將回傳值擴展為lower and 更高的變數
rsi_list = [
14, 88, 56, 74, 25, 22, 41, 55, 31, 98, 44, 56, 24,
43, 87, 15, 91, 71, 14, 16, 33, 38, 4, 6, 3, 78
]
lower, higher = sort_low_high(rsi_list)
print('< 50:', lower)
print('> 50:', higher)
# Output
# < 50: [14, 25, 22, 41, 31, 44, 24, 43, 15, 14, 16, 33, 38, 4, 6, 3]
# > 50: [88, 56, 74, 55, 98, 56, 87, 91, 71, 78]
uj5u.com熱心網友回復:
當您想根據現有串列的值創建新串列時,您可以在 Python 中使用“串列理解”,它提供了更短的語法。來源:https : //www.w3schools.com/python/python_lists_comprehension.asp
def sort_rsi_low(x):
return [a for a in x if a < 50]
print(sort_rsi_low(rsi_list))
def sort_rsi_high(x):
return [a for a in x if a > 50]
print(sort_rsi_high(rsi_list))
你可以通過使用Lambdawhich 是一個小的匿名函式來縮短它。來源:https : //www.w3schools.com/python/python_lambda.asp
sort_rsi_low = lambda x: [a for a in x if a < 50]
print(sort_rsi_low(rsi_list))
sort_rsi_high = lambda x: [a for a in x if a > 50]
print(sort_rsi_high(rsi_list))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380919.html
上一篇:遠程辦公時意外摔傷,算工傷嗎?
