True
在循环列表中找到给定当前索引的前一个元素的最佳方法是什么。
例如给出这样的数据
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]
before_e = find_prev('e', my_list, my_list_condition)
# before_e should be 'd'
before_c = find_prev('c', my_list, my_list_condition)
# before_c should be 'g' because it's circular list and the first True element before c is g
after_e = find_next('e', my_list, my_list_condition)
# after_e should output 'f'
after_g = find_next('g', my_list, my_list_condition)
# after_g should output 'c' because it's circular list and the first True element after c is g
您可以使用itertools.cycle
Anditertools.compress
来查找下一个元素,确保循环循环并且只循环需要的项目,但确保条件中的元素被保留,一旦完成,那么查找前一个只是反向查找下一个:
from itertools import cycle, compress
def find_next(c, lst, lst_condition):
condition = lst_condition[:]
condition[lst.index(c)] = 1
elems = cycle(compress(lst, condition))
for elem in elems:
if elem == c:
return next(elems)
def find_prev(c, lst, lst_condition):
return find_next(c, list(reversed(lst)), list(reversed(lst_condition)))
测试:
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_list_condition = [0, 0, 1, 1, 0, 1, 1]
find_prev('e', my_list, my_list_condition) #d
find_prev('c', my_list, my_list_condition) #g
find_next('e', my_list, my_list_condition) # f
find_next('g', my_list, my_list_condition) #c
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句