按重量计算的字典

时间:2016-07-06 11:38:24

标签: python dictionary range

今天我想将运费价格表嵌入到python词典中,我不知道如何开始。

我拥有什么?

I have table with shipping costs and zones.

    +-----------+------+---------+--------+
    |  weight   | Asia | America | Europe |
    +-----------+------+---------+--------+
    | 0-500     |   10 |      15 |      5 |
    | 501-1000  |   13 |      18 |      8 |
    | 1001-2000 |   16 |      21 |     11 |
    +-----------+------+---------+--------+

我尝试了什么?

shipping_costs =    [

                        {
                            "min_w":    0,
                            "max_w":    500,
                            "asia":     10,
                            "america":  15,
                            "europe":   5
                        },
                        {
                            "min_w":    501,
                            "max_w":    1000,
                            "asia":     13,
                            "america":  18,
                            "europe":   8
                        },
                        {
                            "min_w":    1001,
                            "max_w":    2000,
                            "asia":     16,
                            "america":  21,
                            "europe":   11
                        }

                    ]

product_weight = 600

for zone in shipping_costs:
    if zone['min_w'] <= product_weight <= zone['max_w']:
        print('Asia: {}, America: {}, Europe: {}'.format(zone['asia'],zone['america'],zone['europe']))

而且......它有效,但我对搜索方法有疑问。这是正确的方式吗?或者是寻找范围的更好工具?

1 个答案:

答案 0 :(得分:2)

这很好,但你需要纠正你的边缘条件 - 检查“小于或等于”而不是“小于”,或像500这样的情况会产生不正确的结果:

if zone['min_w'] <= product_weight <= zone['max_w']:

此外,还有一个拼写错误 - print函数的右括号当然必须在.format()方法之后:

    print('Asia: {}, America: {}, Europe: {}'.format(zone['asia'],zone['america'],zone['europe']))

也可能:

   print('Asia: {asia}, America: {america}, Europe: {europe}'.format(**zone))