gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:44 25 4
gpt4 key购买 nike

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

我的代码如下:

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. 的提示(它可以用于给定索引不在元组表示的任何范围内的情况)

关于python - 在元组列表中查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49369276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com