【问题标题】:Python: split a text file into multiple working sessionsPython:将文本文件拆分为多个工作会话
【发布时间】:2020-06-26 11:05:56
【问题描述】:

如何定义我的工作人员为test.txt 文件中的前 4 行执行操作,然后进入下一个工作人员并继续处理列表中的下 4 个项目(如 5-8)等等。 (第 3 名工人 9-12)。

代码:

import time

with open("test.txt", "r") as f:
    Mylist = f.readlines()

N = 4
def worker():
    for Item in Mylist:
        #Do Stuff
        print(Item)
    print("Done Session")    
    time.sleep(2)


def main():
    worker()
    worker()
    worker()
    return main()

main()   

test.txt 包含从 1 到 12 的数字:

1
2
3
...
12

输出应如下所示:

1
2
3
4
Done Session
5
6
7
8
Done Session
9
10
11
12
Done Session

同样main() 应该在列表中没有更多项目后停止返回,因此在此示例中它将在列表中的第 12 个项目之后停止循环。

【问题讨论】:

    标签: python python-3.x list function loops


    【解决方案1】:

    您可能需要这个 worker() 函数 check this answer 来迭代具有索引的项目列表:

    def worker():
        for idx, Item in enumerate(Mylist):
            if idx % N == 0:
                print("Done Session")
                time.sleep(2)
            print(Item)
    

    【讨论】:

      【解决方案2】:

      你可以使用范围和读取List的特定索引

      import time
      
      with open("test.txt", "r") as f:
          Mylist = f.readlines()
      
      N = 4
      def worker(index_of_worker):
          for x in range(index_of_worker*4, index_of_worker*4+N):
              print(Mylist[x])
          print("Done Session")    
          time.sleep(2)
      
      
      def main():
          worker(0)
          worker(1)
          worker(2)
          return main()
          
      
      main()   
      

      【讨论】:

        猜你喜欢
        • 2013-04-22
        • 2016-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多