如何得到一个重复n次的数?
How obtain a number what is repeated a n times?
我有一个包含很多数字的文件:
0.98
0.23
0.10
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
10.3
11.9
0.56
...
我想打印数字 0 连续重复 10 次(最少)的行数。考虑到上述输入,输出将是:4(对于行号 4,因为 0 连续重复了 10 次)。文件 list.txt 是一个巨大的文件。我是 Python 的新人。我怎样才能删除以下脚本中的错误:
import ast
values = open("list.txt","r")
values = list(map(int, ast.literal_eval(values.read().strip())))
count=0
length=""
if len(values)>1:
for i in range(1,len(values)):
if values[i-1]==values[i]:
count+=1
else :
length += values[i-1]+" repeats "+str(count)+", "
count=1
length += ("and "+values[i]+" repeats "+str(count))
else:
i=0
length += ("and "+values[i]+" repeats "+str(count))
print (length)
逐行阅读和评估文件。如果找到模式,则循环中断,停止读取文件
import ast
count = 0
lineNb = -1
found = False # False by default
with open("list.txt") as f:
for i,line in enumerate(f): # loop over lines, one-by-one
value = ast.literal_eval(line)
if value == 0:
if count == 0: # first occurrence
lineNb = i # set potential lineNb
count += 1 # increment counter
if count == 10: # desired condition
found = True # now we know we have found the pattern
break # break the for loop
else: # not 0
count = 0 # reset counter
print(found,lineNb) # (True,3) # lineNb is zero-based, 3 = 4th line
with open('consecutive.txt') as f:
c = 0
for i,line in enumerate(f):
if float(line)==0.0:
c+=1
if c == 10:
print(i-8)
break
else:
c=0
输出
4
我有一个包含很多数字的文件:
0.98
0.23
0.10
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
10.3
11.9
0.56
...
我想打印数字 0 连续重复 10 次(最少)的行数。考虑到上述输入,输出将是:4(对于行号 4,因为 0 连续重复了 10 次)。文件 list.txt 是一个巨大的文件。我是 Python 的新人。我怎样才能删除以下脚本中的错误:
import ast
values = open("list.txt","r")
values = list(map(int, ast.literal_eval(values.read().strip())))
count=0
length=""
if len(values)>1:
for i in range(1,len(values)):
if values[i-1]==values[i]:
count+=1
else :
length += values[i-1]+" repeats "+str(count)+", "
count=1
length += ("and "+values[i]+" repeats "+str(count))
else:
i=0
length += ("and "+values[i]+" repeats "+str(count))
print (length)
逐行阅读和评估文件。如果找到模式,则循环中断,停止读取文件
import ast
count = 0
lineNb = -1
found = False # False by default
with open("list.txt") as f:
for i,line in enumerate(f): # loop over lines, one-by-one
value = ast.literal_eval(line)
if value == 0:
if count == 0: # first occurrence
lineNb = i # set potential lineNb
count += 1 # increment counter
if count == 10: # desired condition
found = True # now we know we have found the pattern
break # break the for loop
else: # not 0
count = 0 # reset counter
print(found,lineNb) # (True,3) # lineNb is zero-based, 3 = 4th line
with open('consecutive.txt') as f:
c = 0
for i,line in enumerate(f):
if float(line)==0.0:
c+=1
if c == 10:
print(i-8)
break
else:
c=0
输出
4