系统要求用户输入糖果的名称。如果该甜味剂不存在于列表中,则应通知用户。如果该甜味剂在列表中,则每当列表中提到该甜味剂时,列表都会打印出列表的所有详细信息。例如,如果我输入吉百利:
# List of transactions [[customer, sweet, amount, money, day, month]
lst_sweets = [
["Tom", "Cadbury", 2, 9, 1, 10],
["Rachel", "Galaxy", 5, 10, 1, 9],
["Rachel", "Smarties", 4, 10, 1, 8],
["Lisa", "Gum drops", 10, 9, 1, 7],
["Donald", "Cadbury", 1, 5, 1, 6],
["Marie", "Smarties", 5, 10, 1, 5]
]
def sweet_purchases():
x = input("Enter the sweet name")
p = -1
sum = 0
for i in range(len(lst_sweets)):
item = lst_sweets[i]
name = item[1]
if name == x:
p = i
if p == -1:
print("customer not in list")
else:
sweetx = lst_sweets[p]
print("Name:", sweetx[0], "Sweet:", sweetx[1], "amount:", sweetx[2], "money:", sweetx[3], "day:", sweetx[4], "month:", sweetx[5])
期望输出: 姓名:,汤姆,斯威特:,吉百利,金额:,2,金额:,9,日期:,1,月份:,10 姓名:,唐纳德,斯威特:,吉百利,金额:,1,金额:,5,日期:,1,月份:,6
实际产量: 姓名:,汤姆,斯威特:,吉百利,金额:,2,金额:,9,日期:,1,月份:,10
有人知道为什么它不同时打印出来吗?谢谢
在每个循环上设置
p
的方式是清除上一个匹配项如果您只想打印一些输出,这是最简单的方法。如果要在找到所有行后执行某些操作,则需要累积结果。大概是这样的:
但是“pythonic”方法只是找到列表而不进行处理,就是使用理解:
如果找到多个匹配项,则覆盖
p
,只打印一个匹配项。您应该在循环中打印:相关问题 更多 >
编程相关推荐