我要求用戶從鍵盤輸入年份。例如用戶輸入 2008,如何從用戶輸入年份值的串列中獲取該年份的最大值?
這是我的代碼:
data_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940), (20090108, 970), (20090109, 939), (20090110, 936)]
value_year = 0
input_year = input("Enter year >>>")
for date, value in data_list:
result = str(date)
if result[0:4] == input_year:
if value > value_year:
value_year = value
print ("Maximum of this year:", result, value_year)
輸出應該是這樣的。當用戶輸入 2008 時。怎么做?
Maximum of this year: 20080104 845
uj5u.com熱心網友回復:
您可以使用 python 的內置max()函式。
https://docs.python.org/3/library/functions.html#max
data_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940), (20090108, 970), (20090109, 939), (20090110, 936)]
input_year = input("Enter year >>>")
result = max(
(x for x in data_list if str(x[0])[:4] == input_year),
key=lambda x:x[1]
)
print ("Maximum of this year:", result)
uj5u.com熱心網友回復:
我只是想用你的方式來解決問題,而不是用新演算法來解決這個問題(你可以用更好的方式解決這個問題)所以:
你可以使用 enumerate() 函式和這個:
data_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940), (20090108, 970), (20090109, 939), (20090110, 936)]
value_year = 0
input_year = input("Enter year >>>")
target_index = None
for index, (date, value) in enumerate(data_list):
if str(date)[0:4] == input_year:
if value > value_year:
value_year = value
target_index = index
print ("Maximum of this year:", data_list[target_index][0], data_list[target_index][1])
或者這樣做:
data_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940), (20090108, 970), (20090109, 939), (20090110, 936)]
value_year = 0
target_tuple = None
input_year = input("Enter year >>>")
for data_tuple in data_list:
if str(data_tuple[0])[0:4] == input_year:
if data_tuple[1] > value_year:
value_year = data_tuple[1]
target_tuple = data_tuple
print ("Maximum of this year:", target_tuple[0], target_tuple[1])
uj5u.com熱心網友回復:
data_list = [(20070101, 619), (20070102, 615), (20070103, 614), (20080104, 845), (20080105, 840), (20080106, 835), (20090107, 940), (20090108, 970), (20090109, 939), (20090109, 87893),(20090110, 936),(20090110, 9360)]
ma=0
input=2009
for i,v in enumerate(data_list):
if str(v[0])[:4]==str(input):
ma=max(ma,v[1])
print(ma)
使用 enumerate 函式,您可以輕松遍歷串列并獲得所需的結果
注意:這具有時間復雜度為 O(N) 其中 N= len(data_list)
更好的解決方案 對串列進行排序并找到輸入值的最后一次出現
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528645.html
標籤:Python列表元组
上一篇:根據PandasDataframe中多列的串列值過濾索引值的最快方法?
下一篇:如何列出資料框的特定變數?
