2013-05-09 29 views
0

我現在有 -將文件列入打印最便宜的價格。蟒

showFile = open("products.txt", 'r') 
     lines = showFile.readline() 
     while lines: 
      print(lines) 
      lines = showFile.readline() 
     showFile.close() 
     showFile = open("products.txt", 'r') 
     numbers = [] 
     for line in showFile: 
      tokens = line.split(',') 
      numbers.append(min(t for t in tokens[0])) 
     minValue = min(numbers) 
     print(minValue) 

Products.txt -

'Snicker's, 33, 84 
'Mars', 18.5, 72 
'Bounty', 22, 96 

所以其中33是價格,和84是數量。 和18.5是價格,72是數量等。

即時通訊試圖讓它打印一些像 士力架每單位0.39美元。 火星每單位0.29美元。 賞金是每單位0.23美元。 賞金是最便宜的

幫助表示讚賞:d

+3

開始除以一個數由其他,然後瞭解字符串格式化語法:http://docs.python.org/2/library/string.html#format -string-syntax – Patashu 2013-05-09 23:06:17

+0

你不需要(或者想)兩次打開同一個文件,只需要(1)打印到屏幕然後(2)追加到列表中。使用相同的迭代器(實際上,使用'with'上下文)並同時完成這兩個任務。 – hexparrot 2013-05-09 23:31:23

回答

1

您可以使用print repr(tokens)告訴你什麼是在tokens變量。我建議你補充一下,看看它說什麼。

請注意,Python具有不同類型的值。例如。 "18.5"'18.5'是字符串 - 這些適用於實際上是字符串的事物(例如'Bounty'),但它們不適合數字,因爲您無法對它們進行數學運算。

如果你有一個數字,你會希望將其轉換爲float形式(例如18.5)或int形式(如18)。 Python有這樣做的功能,叫做float()int()。你可以在浮點數和整數上進行正常的數學運算(+-*/)。 (如果上述內容不明確:repr將打印帶有引號的字符串;它不會在浮點數或整數內打印引號,repr將始終爲浮點數打印小數點,從不打印整數)。

請注意,float('18.5')將工作,但float(' 18.5')不會,因爲流浪的空間。如果遇到此問題,請查找strip()函數,該函數刪除字符串中的前導空格和尾隨空格。

+0

+1。許多有用的提示應該足以讓OP完成80%的工作,而不需要爲他做他的工作。但對於其他20%,您需要對字符串格式的解釋。例如,每個單位的'{}爲$ {:. 2f}'。'格式('Snickers',.39285714285714285)'現在OP只需要找出'Snickers'和'0.39285714285714285'在他的程序中的位置。 – abarnert 2013-05-10 00:00:44

0

這是一個解決方案。如果你不熟悉所使用的技術,它可能不會非常易讀,但是一旦你做了,它就非常一致並且易於理解。如果有什麼不清楚的地方,請留言。
查看list comprehension瞭解products = []的工作原理。

#!/usr/bin/env python 

import re 
import sys 

# Gives a list of lists [['Snickers', '33', '84'], ..] 
products = [re.sub('[\n \']', '', p).split(',') for p in open("products.txt", "r")] 

# Probably not a very good way... 
cheapest = ("", sys.float_info.max) 

for p in products: 
    # Converts price and quantity to float from string, and divide them 
    cost = float(p[1])/float(p[2]) 

    if cost < cheapest[1]: 
     cheapest = (p[0], cost) 

    # Snickers is $0.39 per unit 
    print "%s is $%.2f per unit." % (p[0], cost) 

print "\n%s is the cheapest product and costs $%.2f per unit." % cheapest 

產地:

Snickers is $0.39 per unit. 
Mars is $0.26 per unit. 
Bounty is $0.23 per unit. 

Bounty is the cheapest product and costs $0.23 per unit.