假设您有一个列表[1,2,3,4,5,0,0,0,7,8, ...]
。给定当前索引,什么是获取下一个非零索引的最佳方法?例如,如果index为2,则下一个非零的值为3;否则为0。如果是4,则为8。
答案 0 :(得分:1)
a = [1,2,3,4,5,0,0,0,7,8]
def nextZeroIndex(array, start):
nextItems = array[start+1:]
for i, x in enumerate(nextItems):
if x != 0:
return 1 + start + i
print(nextZeroIndex(a, 2)) # 3
print(nextZeroIndex(a, 5)) # 8
print(nextZeroIndex(a, 4)) # 8
答案 1 :(得分:0)
def get_next_index(lst, index):
try:
return next(i + index + 1 for i, n in enumerate(lst[index + 1:]) if n != 0)
except StopIteration:
return None
lst = [1, 2, 3, 4, 5, 0, 0, 0, 7, 8]
get_next_index(lst, 2) # 3
get_next_index(lst, 9) # None
get_next_index(lst, 100) # None
从指定的索引开始遍历列表,直到找到一个不同于零的数字,如果索引超出范围或发现非零,则返回None
答案 2 :(得分:0)
您还可以使用itertools实现此目的:
from itertools import compress,count
start = 4
next = list(compress(count(),l[start+1:]))[0]+start+1
print(next)
output:
8
答案 3 :(得分:0)
您可以拥有一个用于存储所有“有效”索引(非零值)的类,当您要查找从给定索引开始的非零值的下一个索引时,只需搜索下一个有效索引,该索引大于您的起始索引
from bisect import bisect_right
class NextIndexNonZero:
def __init__(self, your_numbers: list):
# filter out the indices for zero values/numbers
valid_indices = filter(lambda x: x[1] != 0, enumerate(your_numbers))
self.valid_indices = list(map(lambda x: x[0], valid_indices))
self.max_index = self.valid_indices[-1]
def find(self, start_index: int) -> int:
if start_index >= self.max_index:
return f'There is no index non-zero greater than {start_index}'
next_index = bisect_right(self.valid_indices, start_index)
return self.valid_indices[next_index]
a = [1, 0, 0, 0, 1, 0, 0 ]
n = NextIndexNonZero(a)
print(n.find(2))
print(n.find(4))
输出:
4
There is no index non-zero greater than 4