Python:选择满足条件的索引范围

时间:2014-03-06 20:02:22

标签: python range

示例输入文件:

index   score
1       0.2
3       0.4
7       1.5
13      1.8
22      1.9
25      1.6
30      0.5
31      0.2
43      1.5
45      1.6
50      0.3
61      0.1

我想要做的是产生一些东西,其中得分> gt的区域的最小和最大索引打印在同一行上,如下所示:

min     max
7       25
43      45

我试图使用for循环来分隔while循环中的输入行,检查第二个元素是否为> = 1,但我让自己感到困惑。任何帮助非常感谢。谢谢!

这是我的尝试,但它很愚蠢,因为它在分割之前调用分割线:

while lp[1] >= 1:  
     for line in file:  
     lp = line.split()  
           if lp[1] >= 1:  
           print(lp[0])  

3 个答案:

答案 0 :(得分:1)

更简单的方法是使用itertools.groupby

from itertools import groupby
with open('abc1') as f:
    for k, g in groupby(f, key=lambda x:float(x.split()[1]) >= 1):
        if k:
            minn = next(g)
            for maxx in g: pass
            print minn, maxx
...             
7       1.5
25      1.6

43      1.5
45      1.6

当然,如果范围长度为1,上述代码将不起作用,我将留给您解决。

答案 1 :(得分:0)

lines = []
with open("this_file.txt", "r") as f:
    for l in f.readlines()[1:]:
        a, b = l.split()
        lines.append( (int(a), float(b) )
bigger_than_one = [ pair for pair in lines if pair[1]>=1. ]
print("min", *min(bigger_than_one, key= lambda x: x[1]))
print("max", *max(bigger_than_one, key= lambda x: x[1]))

未经测试,但你应该知道。

答案 2 :(得分:0)

谢谢你们两位,我从你的答案中学到了一些东西。我最后写了这个:

previousScore = 0
previousID = ""
offpeak = True

for line in file:
        lp = line.split()
        if float(lp[1]) >= 1 and offpeak:
                print(lp[0]) 
                offpeak = False
        if float(lp[1]) <= 1 and previousScore >=1:
                print(previousID) 
                offpeak = True
        previousScore = float(lp[1])
        previousID = lp[0]