在给定的python脚本中将“while”替换为“for”

时间:2011-08-03 18:01:56

标签: python

我在python中编写了以下脚本,工作正常:

from sys import argv

script, filename = argv

def brokerage(cost):
    vol = 100
    tamt = cost*vol
    br = (((cost*0.1)/100)*vol)*2
    rc = (0.0074*tamt)/100
    stt = (0.025*tamt)/100
    std = (0.004*tamt)/100
    stb = (11*br)/100
    tbr = br+rc+stt+std+stb
    return(tbr)

cost1 = 10
cost2 = 510

while cost1 < 501 and cost2 < 1001:
    value1 = brokerage(cost1)
    value2 = brokerage(cost2)
    # Can't write 'float' to file so, changed it into string. Don't know why.
    x1 = str(value1)
    x2 = str(value2)
    line = "  |%d\t\t%s\t|\t|%d\t\t%s\t|" % (cost1, x1, cost2, x2)
    # use 'a' in 'open' function to append it, will not overwrite existing value
    # as with 'w'.
    save = open(filename, 'a')
    save.write(line)
    save.write("\n  |---------------------|\t|-----------------------|\n")
    save.close
    cost1+=10
    cost2+=10

现在而不是“while”我想使用“for”来改变代码结构。

3 个答案:

答案 0 :(得分:3)

for cost1,cost2 in zip(range(10,501,10),range(510,1001,10)):
    # your code

或更快:

for cost1 in range(10,501,10):
    cost2 = cost1 + 500
    # Your code

答案 1 :(得分:2)

for cost1, cost2 in zip(range(10, 501, 10), range(510, 1001, 10))):
    # remove these
    # cost1+=10
    # cost2+=10

答案 2 :(得分:0)

for cost1 in range(10, 501, 10):
    # Your code here...
    cost2 = cost1 + 500

(未经测试)