如何使用一系列其他值对一个值进行模数设计?

问题描述 投票:0回答:2

我正在用文本文档中的行填充列表。文本文档是一个日志文件,包含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)
python-3.x for-loop range modulo
2个回答
0
投票
file = open('test.txt')
lines = file.readlines()
data = list()
loopcount = 0
for line in lines:
  if loopcount % 108 < 65:
    data.append(line)
  loopcount += 1

0
投票

试试这个:

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)
© www.soinside.com 2019 - 2024. All rights reserved.