Python迭代效率

时间:2014-09-26 02:52:01

标签: python

如何提高此代码的效率?我不想继续为每个状态重复if语句,只想要一个函数或一大块代码。在这段代码的开头,我有一个字典数组,其中包含50个州中每个州的关键和价值配对及其相应的销售税。如何创建一个从每个键拉出的函数?

if state == 'Alabama':
    state = state_taxes['Alabama']
    tax = state * meal
    total = meal + tax + tip
    print "Your total is: $" + "%.2f" % total
elif state == 'Alaska':
    state = state_taxes['Alaska']
    tax = 0
    total = meal + tax + tip
    print "Your total is: $" + "%.2f" % total
elif state == 'Arizona':
    state = state_taxes['Arizona']
    tax = state * meal
    total = meal + tax + tip
    print "Your total is: $" + "%.2f" % total
等等等..........

3 个答案:

答案 0 :(得分:6)

为什么if语句呢?你不能这样做:

state_tax = state_taxes[state]
tax = state_tax * meal
total = meal + tax + tip
print "Your total is: $" + "%.2f" % total

答案 1 :(得分:1)

许多州都有复杂的税率。例如,有些人higher alcohol tax

您可以为多个数据项设置嵌套的词典:

>>> state_taxes={
...     'Alabama': {"Rate": 0.04}, # etc
...     'Alaska': {"Food Rate": 0.08, "Alcohol Rate": 0.21}
...     # etc...
... }

然后分级访问:

>>> state_taxes['Alabama']['Rate']
0.04

所以你可以这样做:

tax=(state_taxes['Alaska']['Food Rate']*food_cost + 
     state_taxes['Alaska']['Alcohol Rate'] * drink_cost)

答案 2 :(得分:0)

我假设您的state_taxes词典包含与每个州的税收一致的浮动(例如,在您的代码中,您有'阿拉斯加'为税而不是计算它返回0从state_taxes字典可以看出阿拉斯加的州税为0。从那里你根本不需要使用if声明,你可以简单地查询税收的价值。请注意,最好不要使用不同类型的值覆盖state变量(在您的示例中,首先使用state表示状态名称,然后使用state该州的税收。)

state = 'Alabama' #or 'Alaska', or whatever you set this to
state_tax = state_taxes[state]
tax = state_tax * meal
total = meal + tax + tip
print "Your total is: $" + "%.2f" % total

请注意,这假设您的状态始终位于state_taxes词典中。如果您的状态变量的值不在state taxes

的键中,您将需要添加一些错误处理