我有以下元組:
my_list = (1000, 3000, 7000, 15000 ,79000)
對于我給selected變數的任何給定數字,我想回傳元組中的值減去 theinterval和選定的值。間隔是指所選值與我要輸出的前一個值之間的增量/差異。有關進一步說明,請參閱 FAB 的評論。我在說間隔時說的是位置/索引。
比方說,例如:
selected = 79000
interval = 2
預期產量:(7000、79000)
或者
selected = 7000
interval = 1
預期輸出:(3000、7000)
請注意,預期輸出中值的順序遵循元組中值的順序。因此,永遠不會在較小的數字之前輸出較大的數字。
我希望兩個值都在的輸出是元組,例如 (3000, 15000) 或串列 [3000, 15000]。
uj5u.com熱心網友回復:
可能有更好的方法,但請參閱下面的方法:
def getInterval(myList: list, selected, interval) -> tuple:
idxSelected = myList.index(selected)
return (myList[idxSelected - interval], myList[idxSelected])
my_list = [*range(1, 15)]
selected = 4
interval = 3
print(getInterval(my_list, selected, interval))
uj5u.com熱心網友回復:
my_list = (1, 2, 3, 4, 5)
selected = 5
interval = 2
difference = selected-interval
if my_list.index(difference) < my_list.index(selected): #To check if the Difference Value comes before the Selected Value
print(difference, selected)
else:
print(selected, difference)
uj5u.com熱心網友回復:
my_list = (1, 2, 3, 4 ,5)
selected = 5
interval = 2
selected_location = my_list.index(selected) #Here, 4
try:
print([my_list[selected_location-interval], my_list[selected_location]]) #(3, 5)
except:
print([my_list[selected_location], my_list[selected_location interval]]) #Incase the selected variable is on index 1, then 1-2 would give -1, which is not the desired index
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/521508.html
上一篇:如何將密碼存盤在變數中?
下一篇:檔案中的有效行和損壞行
