如何通過在第二個元素中找到最小的正數來回傳元組串列中的第一個元素?
例如
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
回傳 1?
uj5u.com熱心網友回復:
您可以通過將原始串列一分為二,然后確定第二個串列中的最小正值來做到這一點。然后,您可以通過將最小值傳遞給索引來列印索引,或者在原始串列中使用方括號表示法來回傳元組本身。
#Create the list
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
#Split the tuple into two lists
first_element = [i[0] for i in a_list]
second_element = [i[1] for i in a_list]
#Find the smallest positive
smallest = min([i for i in second_element if i > 0])
#Return the index
where_in_list = second_element.index(smallest)
#Method 1
print(where_in_list)
#Method 2
a_list[where_in_list]
方法 1 的輸出為 1,方法 2 的輸出為 (1, 2)。
uj5u.com熱心網友回復:
嘗試:
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
#Currently set min value to first value for comparison
min = a_list[0][0]
#Loop through tuples in list
for n in range(len(a_list)):
#If first value is 0, make min the next value for comparison
if min == 0:
min = a_list[n 1][0]
#To replace min value if the current value in iteration is less than the minimum value
if a_list[n][0] < min and min != 0:
min = a_list[n][0]
print(min) #To see minimum value
uj5u.com熱心網友回復:
您可以將第二個元素分配給另一個變數
例如。
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
tuple = a_list[1] #as the counting goes 0,1,2....
if tuple[0]>tuple[1]:
greater_no = tuple[0]
else:
greater_no = tuple[1]
希望它有效,對不起,我沒有測驗過,但這是我的猜測
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439264.html
