找到一个在 2 列之间连续重复 n 次的数字
find a number that is repeated between 2 columns, n consecutive times
我想找出文本文件中两列之间重复 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
你能帮我修一下吗?非常感谢
在比较值并将值转换为浮点数之前,您需要拆分每一行。
试试这个代码。为了测试,它搜索 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
我想找出文本文件中两列之间重复 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
你能帮我修一下吗?非常感谢
在比较值并将值转换为浮点数之前,您需要拆分每一行。
试试这个代码。为了测试,它搜索 2 个连续的行。为您的 运行.
将其更改为 500ss = '''
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