如何使用2个FOR循环重写它?

2024-04-25 12:35:30 发布

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

这是片段。如何重新编写此代码以消除第一个WHILE循环?在

start = 1
end = 4
currentcount = 0
while start < end:

    file = open('C:\Users\Owner\Desktop\\test' + str(start) + '.txt')
    for line in file:    

        f = o.open('http://www.test.com/?userid=' + line.strip())
        f.close()
        time.sleep(10)

        currentcount += 1

    start += 1

Tags: 代码testtxtlineopenstartusersfile
3条回答

将while循环改为:

for i in range(start, end):

然后在方法体中使用i。其他要点:

  • 使用start作为计数器可能会令人困惑。如果更改start的值,它将不再是开始。在
  • 使用原始字符串作为路径: r'C:\Users\Owner\Desktop\test'
  • 考虑使用str.format来构建字符串,而不是字符串连接。在

在Python2.x中,xrange可能比range稍高一些,尽管考虑到所涉及的数字的大小,这可能不是一个重要的问题。在

currentCount = 0
for start in range(1, 4):
    file = open('C:\\Users\Owner\\Desktop\\test' + str(start) + '.txt')
    for line in file:    

        f = o.open('http://www.test.com/?userid=' + line.strip())
        f.close()
        time.sleep(10)

        currentcount += 1
currentcount = 0  
for i in range(1, 4):      
    file = open('C:\\Users\\Owner\\Desktop\\test' + str(i) + '.txt')      
    for line in file:               
        f = o.open('http://www.test.com/?userid=' + line.strip())          
        f.close()          
        time.sleep(10)            
        currentcount += 1

您可以使用其他一些list iteration/lambda方法,但这应该是您所要寻找的,因为它消除了外部while循环,并且仍然易于阅读。在

相关问题 更多 >