我正在用Python为Burger shop开发一个应用程序网络,该应用程序将从数据库中获取一些数据,我需要管理这些数据
从数据库中,我将得到一个像这样的元组列表 check_table = [(1,'Classic','Cheddar','medium'),(2,'Big','Cheddar','rare'),(3,'Classic','Cheddar','rare') ]
在这里,我试图根据烹饪水平来获取适当数量的牛排,例如稀有,中等,做得很好
我花了很多时间,但是我得不到正确计数的代码,我什至试图制作类似
的语句如果check_table [x] [y] ==“经典”和check_table [x] [y] ==“稀有”:
牛排+ = 1 稀有+ = 1
代码如下:
check_table = [(1,'Classic', 'Cheddar', 'Medium'), (2,'Big', 'Cheddar', 'Rare'), (3,'Classic', 'Cheddar', 'Rare')] # Variables steaks = 0 rare = 0 medium = 0 w_done = 0 # Getting all the data from a nested for for x in range(len(check_table)): for y in range(len(check_table[0])): # Getting the number of steaks if check_table[x][y] == "Classic": steaks += 1 # Getting the style of the steak if check_table[x][y] == "Rare": rare += 1 elif check_table[x][y] == 'Medium': medium += 1 elif check_table[x][y] == 'Well-done': w_done += 1 elif check_table[x][y] == "Big": steaks += 2 # Getting steak style if check_table[x][y] == 'Rare': rare += 2 elif check_table[x][y] == 'Medium': medium += 2 elif check_table[x][y] == 'Well-done': w_done += 2 print("# Steaks ", steaks) print("# Rare ", rare) print("# Medium ", medium ) print("# Well-done ", w_done)
我希望得到这样的东西 牛排4 稀有3 中1 做得好0
因为一个经典汉堡包含一个牛排,而一个大汉堡包含两个牛排,所以我得到了它,就像if语句不在那里一样
牛排4 稀有0 中0 做得好0
希望有人可以帮我解决这个问题,谢谢大家
答案 0 :(得分:1)
check_table = [(1,'Classic', 'Cheddar', 'Medium'), (2,'Big', 'Cheddar', 'Rare'), (3,'Classic', 'Cheddar', 'Rare')]
# Variables
steaks = 0
rare = 0
medium = 0
w_done = 0
# Getting all the data from a nested for
for x in check_table:
print(x)
# Getting the number of steaks
if x[1] == "Classic":
steaks += 1
# Getting the style of the steak
if x[3] == "Rare":
rare += 1
elif x[3] == 'Medium':
medium += 1
elif x[3] == 'Well-done':
w_done += 1
elif x[1] == "Big":
steaks += 2
# Getting steak style
if x[3] == 'Rare':
rare += 2
elif x[3] == 'Medium':
medium += 2
elif x[3] == 'Well-done':
w_done += 2
print("# Steaks ", steaks)
print("# Rare ", rare)
print("# Medium ", medium )
print("# Well-done ", w_done)
答案 1 :(得分:1)
您应该尝试将所有这些if/elif
语句转换为某种数据结构的查找。这将使所有内容更易于推理,更易于编辑,并使您的代码更加简洁。
例如,与其检查if / elif多少牛排,不如查看经典牛排与大牛排的区别:
steak_count = {
'Classic': 1,
'Big': 2
}
count = steak_count['Big'] # 2 steaks for 'Big'
现在,如果您添加其他类型的汉堡,则无需再次编写整套if/elif
语句。您可以通过以下方式将此想法传达给其他人:
check_table = [(1,'Classic', 'Cheddar', 'Medium'), (2,'Big', 'Cheddar', 'Rare'), (3,'Classic', 'Cheddar', 'Rare')]
steak_count = {
'classic': 1,
'big': 2
}
# Variables
counts = {
'steaks': 0,
'rare': 0,
'medium': 0,
'w_done': 0
}
for order_num, steak, cheese, cooked in check_table:
count = steak_count[steak.lower()]
counts['steaks'] += count
counts[cooked.lower()] += count
print(counts)
# {'steaks': 4, 'rare': 3, 'medium': 1, 'w_done': 0}