【问题标题】:find a number that is repeated between 2 columns, n consecutive times找到一个在 2 列之间重复的数字,连续 n 次
【发布时间】:2020-10-13 04:03:15
【问题描述】:

我想从文本文件中找出两列之间在 n 次中重复的行数,例如 500 次。

我的文本文件是这样的(有很多行):

0.85    0.00    1
0.85    0.45    2
0.97    0.14    3
0.91    0.05    4
0.97    0.97    5
0.0     0.1     6
0.45    0.0     7
0.0     0.0     8
0.0     0.0     9
0.0     0.0     10

我的脚本尝试是:

with open('list.txt') as f:
    c = 0
    for i in f:
         for w in i:
            if w[0] == w[1]:
               c+=1
            if c == 500:
                print(i-498)
                break
            else:
                c=0
                print(i)

我想要行数(第 3 列),例如数字 0 在第 1 列和第 2 列中至少连续重复 500 次。输出将是这样的(假设从第 8 行开始,0 是在第 1 列和第 2 列之间重复 500 次)

0.0     0.0     8
0.0     0.0     9
0.0     0.0     10

你能帮我解决它吗?非常感谢

【问题讨论】:

    标签: python file time-series multiple-columns repeat


    【解决方案1】:

    您需要在比较之前拆分每一行并将值转换为浮点数。

    试试这个代码。为了测试,它搜索 2 个连续的行。将其更改为 500 以供您运行。

    ss = '''
    0.85    0.00    1
    0.85    0.45    2
    0.97    0.14    3
    0.91    0.05    4
    0.97    0.97    5
    0.0     0.1     6
    0.45    0.0     7
    0.0     0.0     8
    0.0     0.0     9
    0.0     0.0     10
    '''.strip()
    
    with open ('list.txt','w') as f: f.write(ss)  # write test file
       
    #############################
    
    rep = 2   # change to 500
    with open('list.txt') as f:
        c = 0
        for i in f:
            w = [float(n) for n in i.strip().split()]
            if w[0] == w[1]:
               c+=1
               if c == rep:
                  print('>>> line', int(w[2]))
                  break
            else:
                c=0
                print(i.strip())
    

    输出

    0.85    0.00    1
    0.85    0.45    2
    0.97    0.14    3
    0.91    0.05    4
    0.0     0.1     6
    0.45    0.0     7
    >>> line 9
    

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多