Py学习  »  Python

用于在值小于输入值时打印库存的python字典

Sachin Sharma • 4 年前 • 891 次点击  

计算机商店通过使用python字典管理其笔记本电脑库存。每一个字典条目都有一个特定笔记本电脑型号的字符串名作为键,它在库存中的整数量作为对应的值。

例如:

d = {"MS Surface":47, "HP Laptop Probook":144, "MacBook Pro":23, "Dell Laptop XPS": 10, "Asus Chromebook": 20}

定义一个函数low_inventory(laptop_dict,threshold),它返回laptop inventory laptop_dict中数量小于int threshold(<)的所有条目的名称列表。

示例:作为total_items(d,47)调用函数应返回:

['MacBook Pro', 'Dell Laptop XPS', 'Asus Chromebook']
def low_inventory(laptop_dict, threshold):
    for akey in laptop_dict.keys():
        if laptop_dict[akey] < threshold:
                ----

你能建议一下怎么做吗?我是python新手,在输出方面很吃力。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47224
 
891 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Mark Meyer
Reply   •   1 楼
Mark Meyer    4 年前

您需要返回一个列表,以便可以从定义一个列表开始。类似于:

low_inv = []

在你的圈子里 append() 如果库存不足,则该列表的键(在本例中是计算机的名称)。然后返回:

d = {"MS Surface":47, "HP Laptop Probook":144, "MacBook Pro":23, "Dell Laptop XPS": 10, "Asus Chromebook": 20}

def total_items(laptop_dict, threshold):
    low_inv = []                           # new list
    for akey in laptop_dict.keys():
        if laptop_dict[akey] < threshold:
            low_inv.append(akey)           # append to it
    return low_inv                         # return it

total_items(d,47)

#['MacBook Pro', 'Dell Laptop XPS', 'Asus Chromebook']

这也可以作为 list comprehension ,它将一次性创建一个列表,而不使用显式循环:

def total_items(laptop_dict, threshold):
    return [akey for akey, inv in laptop_dict.items() if inv < threshold]
brandonwang
Reply   •   2 楼
brandonwang    4 年前

你可以用 d.items() 在给定键和值的字典上迭代。试试这样的:

def low_inventory(laptop_dict, threshold):
    low = []
    for key, value in laptop_dict.items():
        if value < threshold:
            low.append(key)
    return low
Logan Murphy
Reply   •   3 楼
Logan Murphy    4 年前

你可以试试滤镜

value = filter(lambda x: dict[x] < 3, keys)

以及其他迭代函数

http://book.pythontips.com/en/latest/map_filter.html