试图用dict缩短我的代码

时间:2013-03-21 14:22:39

标签: python if-statement dictionary int

tala = int(input('Skrifaðu magn af pening-->'))
if tala >= 0:
    fth = int(tala / 5000)
    remains = tala % 5000
    tth = int(remains / 2000)
    remains = remains % 2000
    th = int(remains / 1000)
    remains = remains % 1000
    fhr = int(remains / 500)
    remains = remains % 500
    hdr = int(remains / 100)
    remains = remains % 100
    fty = int(remains / 50)
    remains = remains % 50
    ten = int(remains / 10)
    remains = remains % 10
    fiv = int(remains / 5)
    remains = remains % 5
    one = int(remains / 1)
    print(d[tala])

打印部分是问题的主要焦点 我不熟悉语法,但计划是使用dict来避免大量的if如果数字大于5000或者大于2000等,告诉代码该怎么做。 基本上我有这样的想法(无效的语法)

d = {}
##d[Value between 0 and 4] or d[value between 5 and 9] etc.
d[0-4] = ("That would be {0} Krónur.".format(one))
d[5-9] = ("That would be {1} Fimmkallar and {0} Krónur.".format(one,fiv))
d[10-49] = ("That would be {2} Tíkallar, {1} Fimmkallar and {0} Krónur.".format(one,fiv,ten))
d[50-99] = ("That would be {3} Fimmtíukallar, {2} Tíkallar, {1} Fimmkallar and {0} Krónur.".format(one,fiv,ten,fty))

如果你想知道这段代码在做什么,就是说我输入一个高于5000的值

它会将它拆分(类似于ATM)多少次,即5000张账单,2000张账单,1000张账单,500张账单,100个硬币等等。

这是一个围绕%符号使用的学校项目(它是为C#制作的,但是我通过在Python中进行C#分配来学习python)

主要问题是:如果这是一种使字典样式有效的方法,我很想知道如何。 次要问题是: 如果有更好的方法来做到这一点,我很想听听你的想法。 如果我应该这样做(或其中的一部分),其他方式也不会有任何伤害。

编辑:我找到了一个半功能解决方案,但它并不完美。然而它比我的替代品更具可读性,所以它总比没有好,没有人有比这更好的想法吗?:

#Dictionary START
    if tala < 5:
        num = 0
    elif tala < 10:
        num = 1
    elif tala < 50:
        num = 2
    elif tala < 100:
        num = 3
    d = {}
    d[0] =("Það eru {0} Krónur.".format(one))
    d[1] =("Það eru {1} Fimmkallar og {0} Krónur.".format(one,fiv))
    ...
#Dictionary END
    print(d[num])

3 个答案:

答案 0 :(得分:0)

首先,创建一个字典,将单位名称映射到先前提取的值:

d = {"Kronur": one, "Tikallar": ten, "Fimmtiukallar": fty, ...}

您可以使用collections.OrderedDict来保留项目添加到词典中的顺序。但是,正如其他人指出的那样,使用元组列表可能会更好,因为您更关心订单而不是快速随机访问:

d = [..., ("Tikallar", ten), ("Fimmkallar", fiv), ("Kronur", one)]

现在,您可以遍历字典中的项目(不是0的项目)并将它们连接成一个长字符串。 (使用元组列表时,请使用for (key, val) in d代替for (key, val) in d.items()。)

def get_string(d):
    s = "That would be "
    not_zero = [(key, val) for (key, val) in d.items() if val > 0]
    for i, (key, val) in enumerate(not_zero):
        if i > 0:
            s += ", " if i < len(not_zero)-1 else " and "
        s += "%d %s" % (val, key)
    s += "."
    return s

示例输出:

>>> d = {"Kronur": 4, "Tikallar": 0, "Fimmtiukallar": 2}
>>> print get_string(d)
"That would be 2 Fimmtiukallar and 4 Kronur."

答案 1 :(得分:0)

如果您首先指定所有面额的列表,然后,您可以使用for循环迭代每个面额,然后使用列表推导来输出子串数组。以下是一些测试的例子。

#specify array containing denominations as a tuple, amount and name
denominations = [(5000, 'five thousand'), (2000, 'two thousand'), (1000, 'five thousand'), (500, 'five hundred'), (100, 'one hundred')]

def print_break_down(total):

    counts = []
    for denomination in denominations:
        counts.append(total/ denomination[0])
        total = total % denomination[0]

    main = ' and '.join(['%s %s' %(count, denominations[i][1]) for i, count in enumerate(counts) if count>0])
    print 'That would be %s' % main

print_break_down(15000)
print_break_down(15100)
print_break_down(5300)
print_break_down(4000)
print_break_down(1600)
print_break_down(600)
print_break_down(100)

答案 2 :(得分:0)

这应该可以正常工作,而不是使用dict,因为没有使用查找,所以有利于 dict丢失了

def test_func(value):
    """
        >>> test_func(0)
        'That would be 0 Kronur.'

        >>> test_func(4)
        'That would be 4 Kronur.'

        >>> test_func(5)
        'That would be 1 Fimmkallar and 0 Kronur.'

        >>> test_func(15)
        'That would be 1 Tikallar, 1 Fimmkallar and 0 Kronur.'

        >>> test_func(47)
        'That would be 2 Fimmtiukallar, 0 Tikallar, 1 Fimmkallar and 2 Kronur.'
    """
    twenty = value / 20
    ten = (value - twenty * 20) / 10
    five = (value - twenty * 20 - ten * 10) / 5
    one = (value - twenty * 20 - ten * 10 - five * 5)
    ranges = [((0, 5), 'That would be {0} Kronur.'),
              ((5, 10), 'That would be {1} Fimmkallar and {0} Kronur.'),
              ((10, 20), 'That would be {2} Tikallar, {1} Fimmkallar and '
                         '{0} Kronur.'),
              ((20, 50), 'That would be {3} Fimmtiukallar, {2} Tikallar, '
                         '{1} Fimmkallar and {0} Kronur.')]
    text = next(v for r, v in ranges if r[0] <= value < r[1])
    return text.format(one, five, ten, twenty)

http://docs.python.org/2/library/doctest.html