简体   繁体   English

如何创建一个像圆/循环这样的数组列表?

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

i have an array list, i find a point in the list i require and then take 3 values from that point right, however while this works perfect, i am worried due that if the value was the last value in the list it would error, instead i would want it to loop around to the start of the list again 我有一个数组列表,我在列表中找到了我要的一个点,然后从该点开始取3个值,但是,尽管这样做很完美,但我担心如果该值是列表中的最后一个值,则会出错,相反,我希望它再次循环到列表的开头

for example if it picked zi would then want it to also pick a and b as well 例如,如果选择了zi,则希望它也选择a和b

this is my current code : 这是我当前的代码:

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))

what function or library can i use that achieves this ? 我可以使用什么函数或库来实现此目的?

Thanks 谢谢

You can generate the indices you want using a range , then wrap the indices round to the start of a list using the modulus % operator within a list comprehension - something like: 您可以使用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