[英]Python list how to get item from last to first again?
我需要順序地進行迭代,直到找到或最大化。 例如:
ds = [1,2,3,4,5,6,7,8,9]
tmp = 3 # start (variable)
max = 5 # maximize (variable)
target = 8
所以輸出:[4,5,6,7,8]對不起,我的英語不好。
作為一種非常簡單的方法,您可以在具有相同列表的串聯中建立索引。
但是,從內存角度來看,肯定不是最佳解決方案。
# ds = [1,2,3,4,5,6,7,8,9]
start = 4
length = 7
res = (ds + ds)[start:start+length]
# [5, 6, 7, 8, 9, 1, 2]
嘗試:
>>> ds
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> (ds * ((5+6)//len(ds) + 1))[5:5+6]
[6, 7, 8, 9, 1, 2]
現在5
是您的開始位置5+6
是您的結束位置。 您要遍歷整個數據集,以包含結束位置的次數進行多次,因此: ((5+6)//len(ds) + 1)
如果您的起始位置是第二個或更晚的重復位置(因此,如果您的位置> 8
可以通過從兩個起始位置減去: (startPosition//len(ds)) * len(ds)
將其移回位置和結束位置。
有內置的方法可以做到這一點。
new_data = i[starting_index : ending_index]
如果要獲取列表的其余部分,可以將數字留空。 喜歡:
>>>i = [0,8,9,4]
>>>i[1:]
[8,9,4]
看到此解決方案,我使用了for循環來達到目標
ds = [1,2,3,4,5,6,7,8,9]
tmp = 3 # start (variable)
max = 5 # maximize (variable)
target=8
i=0 # itiration to loop on the list
for x in ds:
if ds[i]<tmp: #till now we didnt reach start point
i=i+1
else:
print(ds[i])
i=i+1
if i == target: #since the target has been reached
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.