python - 如何返回输入元组包含空集的函数?
问题描述
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,如输入所示。
解决方案
您应该在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
推荐阅读
- python - Python 中的“for ... in”循环是否会增加空间复杂度?
- javascript - 将图像对象作为函数和类参数传递
- python - list() 函数的反函数是什么
- rust - 我如何“折叠”嵌套的 `if let` 语句,它们都在其 `else` 子句中运行相同的代码?
- javascript - NodeJS 创建一个 REST Post API
- reactjs - React - 上下文提供程序中的多个不相关值
- python - 端口扫描结果导出为 CSV
- reactjs - 在 React Native 中从 firebase 获取数据
- html - 如何使用 html 和 css 在图片上添加黑色叠加层
- html - 在 HTML 中使用 SVG 创建一个等边三角形,底边和高度为 100px