问题描述
我试图在列表中找到大于某个数字的第三个顺序值的索引。例如,在下面的示例中,我想标识3个大于1的值的索引,该索引将返回值为1.4的索引。通过下面尝试的代码,我正在获取1.3值。
我尝试使用枚举,但这将返回总的第3个索引,而不是第3个顺序值。
是否有一种方法可以识别条件大于1的连续第三个值?
listtest = [0.56,1.25,0.8,1.2,1.3,1.4,2,1.6]
indexBDF = [i for i,n in enumerate(listtest) if n >= 1 ][2]
print(listtest[indexBDF])
上面的代码返回1.3,因为它是大于1的第三个值。我希望代码返回1.4,因为它是连续大于1的第三个值。
解决方法
使用itertools
的丑陋版本:
>>> next(i
for k,g in groupby(enumerate(listtest),lambda x: x[1] >= 1)
if k
for i,_ in islice(g,2,None))
5
这将找到满足条件的连续项目组,然后尝试读取该组的第三项。第一个是结果。
,您可以使用zip()
,enumerate()
,all()
和for循环将值作为3元组进行分析:
listtest = [0.56,1.25,0.8,1.2,1.3,1.4,1.6]
for idx,values in enumerate(zip(listtest,listtest[1:],listtest[2:]),start=2):
if all(val > 1 for val in values):
print(f'found 3 sequential values {values} > 1 at index: {idx}')
break
输出:
found 3 sequential values (1.2,1.4) > 1 at index: 5
,
只需使用传统的for
循环即可解决此问题:
listtest = [0.56,1.6]
occurrences = 0
for index,elem in enumerate(listtest):
if elem > 1:
occurrences += 1
if occurrences == 3:
print("Element =",elem)
print("Index =",index)
occurrences = 0
else:
occurrences = 0
输出:
Element = 1.4
Index = 5
如果要打印所有可能的组合,可以尝试以下方法:
listtest = [0.56,1.6]
for index,num in enumerate(listtest):
if index+3 < len(listtest) + 1:
num_lst = listtest[index:index+3]
if all(num > 1 for num in num_lst):
print("Element =",num_lst[-1],",Index =",index+2)
输出:
Element = 1.4,Index = 5
Element = 2,Index = 6
Element = 1.6,Index = 7
,
此实现提供了一种通用方法,可找到满足某些任意过滤条件的第n个连续元素,并将其用于包含任何数据类型的列表。
def nth_seq_item_index(item_list: list,n: int,filter: callable):
"""The nth item `n` starts at 1 (i.e. 1st sequential item). The `filter`
is a function returning True or False for an item in the list."""
if n < 1:
raise ValueError("n must be greater than 0")
consec_count = 0
for index,item in enumerate(item_list):
if filter(item):
consec_count += 1
else:
consec_count = 0
if consec_count == n:
return index
return None
listtest = [0.56,1.6]
indexBDF = nth_seq_item_index(listtest,n=3,filter=lambda i: i >= 1)
print(listtest[indexBDF])
输出
1.4