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

时间:2011-01-12 23:14:36

标签: python loops

这是片段。如何重新编写它以取消第一个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

5 个答案:

答案 0 :(得分:2)

将您的while循环更改为:

for i in range(start, end):

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

  • 使用start作为计数器可能会造成混淆。如果您更改start的值,则不再是开始。
  • 使用原始字符串作为路径: r'C:\Users\Owner\Desktop\test'
  • 考虑使用str.format来构建字符串而不是字符串连接。

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

答案 1 :(得分: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

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

有点复杂,但处理最可能的错误并继续卡车运输:

import time
import random

ids      = range(4)
infName  = 'c:/Users/Owner/Desktop/test{0}.txt'.format
outfAddr = 'http://www.test.com/?userid={0}'.format
delay    = lambda: time.sleep(random.randint(5,15))

filecount = 0
usercount = 0
for i in ids:
    try:
        with open(infName(i), 'r') as inf:
            filecount += 1
            for line in inf:
                try:
                    with o.open(outfAddr(line.strip())) as outf:
                        usercount += 1
                except IOError:
                    pass
                delay()
    except IOError:
        pass

答案 4 :(得分:0)

我的看法:

start = 1
end = 4

for count in range(start,end):
    file_name=r'C:\Users\Owner\Desktop\test' + str(count) + '.txt'
    with open(file_name) as file:
        for line in file:    
            with o.open('http://www.test.com/?userid=' + line.strip()) as f:
               pass
            time.sleep(10)