我有一个元组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
但是,如果索引位于列表seg的第一个第二个段中,我也想返回。
例如,1
返回index = 1015
,3
返回<html>
<body>
<a href="http://config_?Token=blah1234">http://config_?Token=blah1234</a>
</body>
</html>
。
我该怎么办?
答案 0 :(得分:8)
您可以将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.的提示(可以在给定索引不在元组表示的任何范围内的情况下使用)
答案 1 :(得分:3)
正如其他人所指出的那样,您可以使用enumerate()
来获取索引。我还认为,如果你将元组视为范围,你应该将它们ranges。然后,检查该值是否在范围内非常直观:value in range
。
import itertools
seg = [(874, 893), (964, 985), (1012, 1031)]
ranges = list(itertools.starmap(range, seg))
def test(value):
for i, valueRange in enumerate(ranges):
if value in valueRange:
return i # + 1 if you want to index from 1 as indicated.
# You could add some special case handling here if there is no match, like:
# throw NoSuchRangeException("The given value was not inside any of the ranges.")
print(test(876)) # 0
print(test(1015)) # 1
显然使用范围有一些成本(如果你在Python 2.x中,这是相当大的,因为它会生成所有值的实际列表,不幸的是xrange()
返回没有__contains__()
实现的对象)。如果你在很多地方做这种事情,那就更好了。
根据具体情况,你可以用范围构造替换你的元组结构,而不是做星图。
答案 2 :(得分:1)
假设如下:
订购清单
第一个数字小于第二个数字
没有重叠
index=870
seg = [(874, 893), (964, 985), (1012, 1031)]
for i, t in enumerate(seg):
if index >= t[0] and index <= t[1]:
print i