Как мне вернуть это в виде списка - PullRequest
0 голосов
/ 04 февраля 2011

У меня есть эти данные:

inventory = { HAMMER: (10,100),
              SCREW: (1, 1000),
              NAIL: (1, 1000),
              SCREWDRIVER: (8, 100),
              DRILL: (50, 20),
              WORKBENCH: (150, 5),
              HANDSAW: (15, 50),
              CHAINSAW: (80, 30)
            }

Который я написал следующую функцию:

def get_items(cheapness):
    """ Return a list of (item, (price, count)) tuples that are the given
    cheapness. Note that the second element of the tuple is another tuple. """

    if cheapness == 'CHEAP':
        return [(key, value) for (key,value) in inventory.items() if value in ((cost,quantity) for (cost, quantity) in inventory.values() if cost < 20)]
    elif cheapness == 'MODERATE':
        return [(key, value) for (key,value) in inventory.items() if value in ((cost,quantity) for (cost, quantity) in inventory.values() if 20 < cost < 100)]
    elif cheapness == 'EXPENSIVE':
        return [(key, value) for (key,value) in inventory.items() if value in ((cost,quantity) for (cost, quantity) in inventory.values() if cost > 100)]

Моя проблема, когда я делаю print type(get_items(CHEAP)), я получаю <type 'NoneType'>,Как вернуть результаты в виде списка?

Ответы [ 3 ]

5 голосов
/ 04 февраля 2011

Этот код более функциональный и его легче поддерживать:

def get_items(cheapness):
    def a(value):
        if cheapness == 'CHEAP':
            return value < 20
        if cheapness == 'MODERATE':
            return value >= 20 and value < 100
        if cheapness == 'EXPENSIVE':
            return value >= 100
        return False
    return filter(lambda x: a(x[1][0]), inventory.items())
3 голосов
/ 04 февраля 2011

Скажите, что вы имеете в виду:

def get_items(cheapness):
    """ Return a list of (item, (price, count)) tuples that are the given
    cheapness. Note that the second element of the tuple is another tuple. """

    if cheapness == 'CHEAP':
        return [(item, (price,count)) for (item, (price,count)) in inventory.items() if price < 20]
    elif cheapness == 'MODERATE':
        return [(item, (price,count)) for (item, (price,count)) in inventory.items() if price > 20 and price < 100]
    elif cheapness == 'EXPENSIVE':
        return [(item, (price,count)) for (item, (price,count)) in inventory.items() if price > 100]
1 голос
/ 04 февраля 2011

как насчет типа печати (get_items ('CHEAP'))?(обратите внимание на цитаты)

...