如何创建一个循环/一个圆?

2024-05-13 22:54:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组列表,我在列表中找到我需要的一个点,然后从该点取3个值,但是当这个操作完美时,我担心如果这个值是列表中的最后一个值,它会出错,相反,我希望它再次循环到列表的开头

例如,如果它选择了z,我希望它同时选择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))

我可以使用什么函数或库来实现这一点?在

谢谢


Tags: the代码列表positionit数组leftresponsible
1条回答
网友
1楼 · 发布于 2024-05-13 22:54:57

您可以使用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']

相关问题 更多 >