我正在嘗試創建一個函式,它將回傳串列中 140 或更高的第一個位置。我的代碼將回傳存在 140 的每個實體。
串列看起來像這樣[[0.1,1.2,12.2,140.1,32],[0.2,2.2,222,11,32],[142,3.2,32.2,140.3,32],[0.4,4.2,42.2,140.4,192],[0.5,5.2,52.2,14.5,32]]
這是功能:
def val_return(prices):
for i in range (0, len(prices)):
for j in range (0, len(prices[i])):
if prices[i][j] > 140:
return (j)
elif prices [i][j] < 139:
pass
uj5u.com熱心網友回復:
=與 140 進行比較時,您的問題似乎在于缺少。此外,該elif部分是額外的:
def val_return(prices):
result = []
for i in range (len(prices)):
for j in range (len(prices[i])):
if prices[i][j] >= 140:
result.append(j)
pass
return result
輸出:
[3, 2, 0, 3]
這是一種更 Pythonic 的作業方式:
def val_return(prices):
return [next((each_element[1] for each_element in zip(each_row, range(len(each_row))) if each_element[0] >= 140), None) for each_row in prices]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441613.html
標籤:Python python-3.x 列表
上一篇:R:如何從列中洗掉嵌套串列?
