如何将一个值与一系列其他值取模?
How to modulo one value with a range of other values?
我正在用文本文档中的行填充一个列表。文本文档是一个日志文件,包括 108 行(条目),重复数百次。
我正在使用 For 循环填充列表,但我只需要前 65 行。
有没有办法让 For 循环跳过第 66-108 行?我正在考虑使用 continue ,如下面的代码所示,使用我希望跳过的行号的模数。
有没有办法将 'if modulo' 与范围一起使用,或者我是否需要为我希望跳过的每一行添加一个 'if modulo' 语句?
file = open('test.txt')
lines = file.readlines()
data = list()
for line in lines:
if loopcount % range(66,108) == 0: #
loopcount += 1
continue
loopcount += 1
data.append(line)
试试这个:
next_loop = False
file = open('test.txt')
lines = file.readlines()
data = list()
for line in lines:
not_read = range(66,108)
#test every num in the list
for i in not_read:
if loopcount % i == 0:
loopcount += 1
next_loop = True
break
if next_loop:
next_loop = False
continue
loopcount += 1
data.append(line)
file = open('test.txt')
lines = file.readlines()
data = list()
loopcount = 0
for line in lines:
if loopcount % 108 < 65:
data.append(line)
loopcount += 1
我正在用文本文档中的行填充一个列表。文本文档是一个日志文件,包括 108 行(条目),重复数百次。
我正在使用 For 循环填充列表,但我只需要前 65 行。 有没有办法让 For 循环跳过第 66-108 行?我正在考虑使用 continue ,如下面的代码所示,使用我希望跳过的行号的模数。 有没有办法将 'if modulo' 与范围一起使用,或者我是否需要为我希望跳过的每一行添加一个 'if modulo' 语句?
file = open('test.txt')
lines = file.readlines()
data = list()
for line in lines:
if loopcount % range(66,108) == 0: #
loopcount += 1
continue
loopcount += 1
data.append(line)
试试这个:
next_loop = False
file = open('test.txt')
lines = file.readlines()
data = list()
for line in lines:
not_read = range(66,108)
#test every num in the list
for i in not_read:
if loopcount % i == 0:
loopcount += 1
next_loop = True
break
if next_loop:
next_loop = False
continue
loopcount += 1
data.append(line)
file = open('test.txt')
lines = file.readlines()
data = list()
loopcount = 0
for line in lines:
if loopcount % 108 < 65:
data.append(line)
loopcount += 1