我正在尝试创建一个卡路里计数器,标准输入如下:
python3 calories.txt < test.txt
在卡路里里面,食物的形式如下:苹果500
我遇到的问题是每当我计算人的价值时,它似乎永远不会返回空列表。
import sys
food = {}
eaten = {}
finished = {}
total = 0
#mappings
def calories(x):
with open(x,"r") as file:
for line in file:
lines = line.strip().split()
key = " ".join(lines[0:-1])
value = lines[-1]
food[key] = value
def calculate(x):
a = []
for keys,values in x.items():
for c in values:
try:
a.append(int(food[c]))
except:
a.append(100)
print("before",a)
a = []
total = sum(a) # Problem here
print("after",a)
print(total)
def main():
calories(sys.argv[1])
for line in sys.stdin:
lines = line.strip().split(',')
for c in lines:
values = lines[0]
keys = lines[1:]
eaten[values] = keys
calculate(eaten)
if __name__ == '__main__':
main()
编辑 - 忘记包含test.txt的内容:
joe,almonds,almonds,blue cheese,cabbage,mayonnaise,cherry pie,cola
mary,apple pie,avocado,broccoli,butter,danish pastry,lettuce,apple
sandy,zuchini,yogurt,veal,tuna,taco,pumpkin pie,macadamia nuts,brazil nuts
trudy,waffles,waffles,waffles,chicken noodle soup,chocolate chip cookie
答案 0 :(得分:0)
如何让自己更轻松:
在阅读卡路里数据时,尽快将卡路里转换为int()
,每次想要总结这样的事情时都不需要这样做。
字典有一个.get(key, defaultvalue)
accessor,所以如果找不到食物,使用100作为默认值是1-liner w / o try: ... except:
这对我有用,不是使用sys.stdin
,而是将第二个文件作为文件提供,而不是使用<
将其传送到程序中。
我修改了一些解析来删除空格并从calc返回一个[(name,cal),...]
元组列表。
它可以帮助您根据自己的喜好进行修复:
def calories(x):
with open(x,"r") as file:
for line in file:
lines = line.strip().split()
key = " ".join(lines[0:-1])
value = lines[-1].strip() # ensure no whitespaces in
food[key] = int(value)
def getCal(foodlist, defValueUnknown = 100):
"""Get sum / total calories of a list of ingredients, unknown cost 100."""
return sum( food.get(x,defValueUnknown ) for x in foodlist) # calculate it, if unknown assume 100
def calculate(x):
a = []
for name,foods in x.items():
a.append((name, getCal(foods))) # append as tuple to list for all names/foods eaten
return a
def main():
calories(sys.argv[1])
with open(sys.argv[2]) as f: # parse as file, not piped in via sys.stdin
for line in f:
lines = line.strip().split(',')
for c in lines:
values = lines[0].strip()
keys = [x.strip() for x in lines[1:]] # ensure no whitespaces in
eaten[values] = keys
calced = calculate(eaten) # calculate after all are read into the dict
print (calced)
输出:
[('joe', 1400), ('mary', 1400), ('sandy', 1600), ('trudy', 1000)]
使用sys.stdin
和管道只是导致我的控制台闪烁并等待手动输入 - 可能VS相关......