如何定义我的工作人员为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项之后停止循环。
发布于 2020-06-26 11:19:16
您可能需要这个worker()函数,check this answer来使用索引来迭代一组项:
def worker():
for idx, Item in enumerate(Mylist):
if idx % N == 0:
print("Done Session")
time.sleep(2)
print(Item)发布于 2020-06-26 11:24:18
您可以使用范围并读取列表的特定索引。
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() https://stackoverflow.com/questions/62593420
复制相似问题