簡體   English   中英

如何創建一個像圓/循環這樣的數組列表?

[英]How to create an array list like a circle / loop?

我有一個數組列表,我在列表中找到了我要的一個點,然后從該點開始取3個值,但是,盡管這樣做很完美,但我擔心如果該值是列表中的最后一個值,則會出錯,相反,我希望它再次循環到列表的開頭

例如,如果選擇了zi,則希望它也選擇a和b

這是我當前的代碼:

descriptor_position = bisect_left(orHashList, b32decode(descriptor_id,1)) #should be identiy list not HSDir_List #TODO - Add the other part of the list to it so it makes a circle
   for i in range(0,3):
      responsible_HSDirs.append(orHashList[descriptor_position+i])
   return (map(lambda x: consensus.get_router_by_hash(x) ,responsible_HSDirs))

我可以使用什么函數或庫來實現此目的?

謝謝

您可以使用range生成所需的索引,然后使用列表理解中的模數%運算符將索引四舍五入到列表的開頭-類似於:

>>> a = ['a', 'b', 'c', 'd', 'e']
>>> index = 4
>>> [x % len(a) for x in range(index, index+3)]

[4, 0, 1]

>>> [a[x % len(a)] for x in range(index, index+3)]

['e', 'a', 'b']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM