Skip to main content
 首页 » 编程设计

python之在元组列表中查找索引

2025年05月04日14yjmyzz

我有一个元组列表 seg = [(874, 893), (964, 985), (1012, 1031)] 和一个索引。我想检查索引是否在这些元组的范围内,例如 876 在 870 不在范围内。

我的代码如下:

if [x for (x, y) in seg if x <= index <= y]: 
   print ("index inside the segment") 

但是,如果索引位于列表段的第一个第二...段中,我也想返回。

例如,对于 index = 876 返回 1 而对于 index = 1015 返回 3。

我该怎么做?

请您参考如下方法:

您可以使用 enumerate + next生成器表达式:

>>> seg = [(874, 893), (964, 985), (1012, 1031)] 
>>> index = 876 
>>> next((i for i, (s,f) in enumerate(seg) if s <= index <= f), None) 
0 

或者,如果你想遍历:

>>> for i in (i for i, (s,f) in enumerate(seg) if s <= index <= f): 
...     print("in segment:", i) 
...  
in segment: 0 

感谢 @jpp 关于 the default option of the next function. 的提示(它可以用于给定索引不在元组表示的任何范围内的情况)