![](/img/trans.png)
[英]how do i create a list of dict in python with the data been read from a text file?
[英]How do I manipulate data in a list that has been read in from a file using Python 2.x?
我正在嘗試創建一個程序來計算配方中原料的成本,並返回所述配方的總成本。 我正在自學Python,並將其設置為個人的但實用的挑戰。 但是,我碰壁了。 硬。
我的想法是將文件讀入列表。 將列表中的成分乘以逗號分隔的數字。 將所有內容加在一起,然后返回一個總費用的浮點數。
#Phase 1 - MASTER INGREDIENTS LIST
flour_5lb = 2.5
sugar_4lb = 2.0
butter_lb = 3.0
eggs_doz = 3.0
#PHASE 2 - COST PER UNIT CONVERSION
flour_cup = flour_5lb*(1.0/20)
sugar_cup = sugar_4lb*(1.0/8)
butter_Tbsp = butter_lb*(1.0/32)
eggs_each = eggs_doz*(1.0/12)
#PHASE THREE - RECIPE ASSESSMENT
def main():
fileObject = open("filname.txt", "r")
fileLines = fileObject.readlines()
fileObject.close()
for line in fileLines:
print line
print "\n"
if __name__ == "__main__":
main()
for line in fileLines:
語句中的for line in fileLines:
輸出以下內容:
flour_cup, .5
milk_cup, .4
eggs_each, 3
butter_Tbsp, 3
Press any key to continue . . .
如果我對您的理解正確,則必須解析文件。 為此,您需要知道成分的存儲格式。 由於此程序僅供您個人使用,因此您可以選擇最簡單的程序。
因此,假設您有CSV格式的配料:
sugar 10g
flour 20g
...
然后,您可以使用python的內置函數split
和迭代來獲取列表[['sugar', '10g'], ['flour', '10g'], ...]
。
將數量放入python浮點數有點棘手,因為我們必須關注單位。
再次-選擇一組固定的單位可以使您的生活更輕松。 然后使用in
語句或內置函數檢查給定字符串是否具有特定后綴。 (我將把它留給您以找到此功能。)
然后,困難的部分就完成了。 希望我能在不付出太多的情況下提供幫助。
您遇到的困難之一就是知道如何在逗號上分割輸入-使用split()
。 另一個問題是將字符串轉換為float -使用float()
。
您的最后一個問題是將輸入字符串映射到值。 您可以編寫一個將字符串映射到成本的函數:
if item == "milk_cup":
return milk_cup
if item == "flour_cup":
return flour_cup
...
...但是更好的方法( DRY )是使用字典。
在下面的示例中,我使用dict()
制作了字典,因為我不必引用每個字符串。
這是一個示例:
#!/usr/bin/python
pricelist = dict(
flour_cup=1.0,
milk_cup=0.4,
)
input = ["flour_cup, 0.5", "milk_cup, 0.4"]
total = 0
for line in input:
item, qty = line.split(",")
item = item.strip()
qty = float(qty)
if item in pricelist:
cost = qty * pricelist[item]
print "%s: %.02f\n" % (item, cost)
total += cost
else:
print "I don't know what '%s' is" % item
print "Total: %.02f" % total
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.