将.text读入定义

时间:2011-11-06 21:57:04

标签: python dictionary

我试图从一个看起来像这样的简单文本文件中读取:

11
eggs
1.17
milk
3.54
bread
1.50
coffee
3.57
sugar
1.07
flour
1.37
apple
.33
cheese
4.43
orange
.37
bananas
.53
potato
.19

我要做的是询问输入文件名,例如“milk”,而不是打印它的价格。我正在尝试使用词典。

这是我的代码:

def main():
    key = ''
    infile = open('shoppinglist.txt', 'r')

    count = infile.readline()
    groceries = {}

    print('This program keeps a running total of your shopping list.')
    print('Use \'EXIT\' to exit.')

    grocery = input('Enter an item: ')

    for line in infile:
        line = line.strip()
        if key == '':
            key = line
        else:
            groceries[key] = line #maybe use here float(line) instead
            key = ''

    print ('Your current total is $'+ groceries[grocery])

main()

预期输出

此程序会保留您购物清单的总计。 使用'退出'退出。 输入项目:eggs 您当前的总额是1.17美元

输入项目:面包 您当前的总金额是$ 3.00

输入一个项目:糖 您当前的总额是4.07美元

输入项目:退出 你的最终总额是4.07美元

2 个答案:

答案 0 :(得分:1)

你有。你已经准备好了代码 看看差异:

- 你正在覆盖groceries
- 你没有从字典中读取值 -In python< 3x你应该使用raw_input而不是输入。如果你在py3k输入就可以了 - 你也不需要在py2.x中打印括号。你在py3k中做 - 也许这里作业唯一奇怪的是在印刷品中使用%。这意味着%s将被最后一个%符号后的字符串替换 - 小心,因为杂货的成本实际上是字符串,所以你不能用它们进行数学运算。首先,你应该将它们转换为浮点数。

def main():
    key = ''
    infile = open('shoppinglist.txt', 'r')

    count = infile.readline()
    groceries = {}

    print('This program keeps a running total of your shopping list.')
    print('Use \'EXIT\' to exit.')

    grocery = raw_input('Enter an item: ')

    for line in infile:
        line = line.strip()     #take out newlines codes.
        if key == '':
            key = line
        else:
            groceries[key] = line     #maybe use here float(line) instead
            key = ''

    print 'Your current total is %s $' % groceries[grocery]

main()

对于多个输入使用(未测试,py3k代码,记得在之前将成本转换为浮点数):

total = 0
while True:
  grocery = input('Enter an item: ')
  if grocery == 'EXIT':
       print('Your final total is $%s' %total)
       break
  else:
       cost = groceries[grocery]
       total += cost
       print('Your current total is $%s' %total)

答案 1 :(得分:0)

两件事:鸡蛋+面包== 1.17 + 1.50!= 3.00 ......

其次,您可以(对于这样一个小文本文件)编写一个例程,通过将偶数/奇数行作为键:值对(或将type()测试为str或float)来预先构建字典,并且弄明白这一点)。重复遍历文本文件比在内存中引用存储的变量花费更多。

此外,这种方法使得第一步的工作变得更加简单,因此您可以专注于第二步,并确保您背后的代码有效,并且有意义。