首页 > 解决方案 > 如何返回输入元组包含空集的函数?

问题描述

CATALOGUE = {("table", 9999, 20), ("chair", 2999, 5), ("lamp", 1999, 10)}      

def add_item_to_order(name, quantity, order):
    number=0
    lookup=[]
    new={}
    catlist=list(CATALOGUE)
    
    for item in name, quantity, order:
        for item in order:
            lookup=list(order)
            for cat in catlist:
                if name==lookup[0][0]:
                    newnumber=number+quantity+lookup[0][1]
                    new={(lookup[0][0],newnumber,lookup[0][2],lookup[0][3])}
                elif name in cat and len(lookup)!=0: 
                    new={(lookup[0][0],lookup[0][1],lookup[0][2],lookup[0][3]),(cat[0],quantity,cat[1],cat[2])}
                elif name in cat and len(lookup)==0:
                    new={(cat[0],quantity,cat[1],cat[2])}
                return new
            else:
                raise KeyError
                    
     
add_item_to_order("table", 1, set())

我有一个任务,其中一个包含名称、数量和顺序(一组)的元组被输入到一个函数中。根据订单是否与名称匹配,函数返回一个新的集合 eg {("table"(name),1 (quantity), 9999(price in pence), 20 (weight)},其中更新数量。如果名称与顺序不匹配,如果名称与目录匹配,则生成一组两个元组,例如{('chair', 1, 2999, 5), ('table', 1, 9999, 20)}。如果输入顺序的集合为空,则返回 CATALOG 中与输入中的名称匹配的一个元组的集合,例如上面的代码应该返回 {("table", 1, 9999, 20}。上面的代码能够为第一个两个条件工作,但是如果输入中的 order 有一个空集,则返回 Nonetype,如输入所示。

标签: pythonlistfunctionsettuples

解决方案


您应该在new每次循环中添加项目,而不是替换整个变量。

return new应该在函数的末尾,而不是在循环内。

并且new应该被初始化为一个集合,而不是一个字典。

for item in name, quantity, order:完全没有意义。您可以使用for item in order:for name, quantity, price, weight in order:。你也不需要嵌套循环,只需要一个循环order

我不明白你为什么要转换order为列表,然后只是测试lookup[0]。您应该item在循环中使用,而不是order.

您无需转换CATALOGUE为列表即可对其进行迭代。

def add_item_to_order(name, quantity, order):
    new = set()
    name_matched = False
    for oname, oquantity, oprice, oweight in order:
        if oname == name:
            name_matched = True
            new.add((name, oquantity + quantity, oprice, oweight))
        else:
            new.add((name, oquantity, oprice))
            
    if not name_matched:
        for cname, cprice, cweight in CATALOGUE:
            if cname == name:
                new.add((name, quantity, cprice, cweight))
                break
        else:
            raise KeyError(f"{name} not found in CATALOGUE")
    
    return new

推荐阅读