[英]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.