如何创建一个循环数组列表?
我有一个数组列表,我在列表中找到一个我需要的点,然后从这个点向右取三个值。不过,我有点担心,如果这个值是列表中的最后一个值,就会出错。其实我想要的是,如果到达了最后一个值,就能重新回到列表的开头。
举个例子,如果它选中了 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))
我可以用什么函数或库来实现这个功能呢?
谢谢!
1 个回答
4
你可以使用一个叫做 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']