【问题标题】:How to modulo one value with a range of other values?如何将一个值与一系列其他值取模?
【发布时间】:2019-03-27 08:21:13
【问题描述】:

我正在用文本文档中的行填充一个列表。文本文档是一个日志文件,包含 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


    【解决方案1】:
    file = open('test.txt')
    lines = file.readlines()
    data = list()
    loopcount = 0
    for line in lines:
      if loopcount % 108 < 65:
        data.append(line)
      loopcount += 1
    

    【讨论】:

      【解决方案2】:

      试试这个:

      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)
      

      【讨论】:

      • 我喜欢这个想法,但不幸的是 continue 将继续新的嵌套 for 循环(for i 而不是 for line)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      相关资源
      最近更新 更多