我是Python的新手,我正在為一個簡單的問題而苦惱。
我有一個600和900之間的數字陣列;我想創建一個函式,根據數字的值回傳一個文本值。
values = array([702, 664, 817, 893, 768, 789, 637, 642, 619, 724] )
def function(x)。
for i in np.nditer(x)。
if 600 <= i <= 699:
x[i] = ('Low')
elif 700 <= i <= 799:
x[i] = ('Med')
else:
x[i] = ('High')
return i
y = function(value)
uj5u.com熱心網友回復:
這就是你要找的東西嗎?
代碼:
values = [702, 664, 817, 893, 768, 789, 637, 642, 619, 724]
def function(x)。
x_out = []
for i in x:
if 600 <= i <= 699:
x_out.append('Low')
elif 700 <= i <=799:
x_out.append('Med')
else:
x_out.append('High')
return x_out
y = function(values)
print(values)
print(y)
輸出:
[702, 664, 817, 893, 768, 789, 637, 642, 619, 724]
['Med', 'Low', 'High', 'High', 'Med'。'Med', 'Low', 'Low', 'Low', 'Med']
uj5u.com熱心網友回復:
我想我明白你想要什么,對于初始陣列中的每個值,列印出其相應的文本("低"、"中 "或 "高")。只要稍微修改一下你的代碼就可以了。
def function(array)。
輸出 = []
for value in array:
if 600 <= value <= 699:
output.append('Low')
elif 700 <= value <=799:
output.append('Med')
else:
output.append('High')
輸出
盡管你是Python的新手,但上面的代碼很容易閱讀/理解,希望如此。你可以玩玩這個函式。
values = array([702, 664, 817, 893, 768, 789, 637, 642, 619, 724] )
output = function(value)
print(output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/321098.html
標籤:
上一篇:如何在python中格式化一個文本檔案(去除不需要的行距和段距)?
下一篇:如何將重復的列轉為行Pandas
