想象一下,您有一個數字串列,并且您想找到滿足特定條件(例如 > 3)的數字索引。然后我們希望最小的索引(滿足上述條件)是某個數字(這里是 4)的倍數。下面可能是一個好的開始。您對其余代碼有何建議?
a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4
output = [i for i, x in enumerate(a) if x > 3]
列印(輸出)'''
uj5u.com熱心網友回復:
如果要查找最小索引,可以使用min()函式:
a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4
output = [i for i, x in enumerate(a) if x > 3]
print(output, min(output))
uj5u.com熱心網友回復:
索引已經通過上面給出的代碼獲得。您需要做的就是找到可被 整除的最小索引b。您可以按如下方式實作:
a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4
# outputGT3 = output of all numbers > 3
outputGT3 = [i for i, x in enumerate(a) if x > 3]
print(outputGT3)
# outputDBb = output of all numbers divisible by b
outputDBb = [x for i, x in enumerate(outputGT3) if x % b==0]
print(outputDBb[0])
# since outputDBb is already sorted, the 1st element is the smallest.
uj5u.com熱心網友回復:
這個問題與串列無關:
a, b = 3, 4
n = a b/2
result = n - (n%b)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/466082.html
上一篇:如何根據每個組件的名稱在串列的所有組件中創建一個新列?
下一篇:如何壓縮多個但未知數量的串列?
