嵌套循环代码不起作用

2024-06-02 07:52:07 发布

您现在位置:Python中文网/ 问答频道 /正文

with open(sys.argv[2]) as f:
     processlist = f.readlines()
     for a in range(0,1):
         process = processlist[a]
         print process
         for b in range(0,3):
             process1 = process.split()
             print process1[b]

你知道吗系统argy[2]文件只有两个句子

Sunday Monday
local owner public

我试着一次读一句话,每句话我试着一次读一个单词。。。。我能够得到的东西,我需要个别,但循环不迭代。。。它在第一次迭代后停止。。。。你知道吗


Tags: infor系统aswithsysrangeopen
2条回答

要回答循环为什么不迭代的问题:

range(0,1)

只包含元素0,因为the upper bound is not included in the result。同样地

range(0,5)

当作为列表查看时,将是[0,1,2,3,4]。你知道吗

@HennyH的答案演示了迭代文件的正确方法。你知道吗

with open(sys.argv[2]) as f:
    for line in f: #iterate over each line
        #print("-"*10) just for demo
        for word in line.rstrip().split(): #remove \n then split by space
            print(word)

你的档案会产生

     
Sunday
Monday
     
local
owner
public

相关问题 更多 >