在元组列表中查找索引

kon*_*tin 1 python indexing tuples

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

我这样做的代码如下:

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

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

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

我怎么能这样做?

Joe*_*don 8

你可以使用enumerate+ nextwith generator expression:

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

或者,如果您想迭代:

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

感谢@jpp有关函数默认选项next的提示.(它可以在给定索引不在元组表示的任何范围内的情况下使用)

  • @theausome来自OP的问题的好地方,但我想我会为了未来的访客而留下它.我确信,如果他们希望元组基于"1",那么他们可以自己做增量:) (2认同)