我正在玩清单,并试图想出一个包含来自不同食物条目的营养素的清单。
所以我基本上想要一次访问一个列:
foodList = [["Liver" , 253, 0],["Spinach" , 844, 45],["Sausage" , 200, 100]]
for x in foodList:
printNow (x[0])
返回:
Liver
Spinach
Sausage
我的列表会比这个大得多,我需要从txt文件中打开它。问题是,当我尝试将txt文件转换为与上面相同格式的列表时,我试图将其停止工作。出于测试目的,这是我在.txt文件中输入该数据的方式。
Liver , 253, 0:
Spinach, 844, 45:
Sausage, 200, 100:
这是我如何将其转换为列表的功能:
list = open('/Users/Danrex/Desktop/nutrientlist.txt', "rt")
read = list.read()
split = read.split("\n")
foodList = []
for x in split:
foodList = foodList + [x.split(":")]
list.close()
for food in foodList:
printNow (food[0])
当我执行此代码时,我将返回:
Liver , 253, 0
Spinach, 844, 45
Sausage, 200, 100
但是除了从测试文件转换它时出现的空元素之外,列表构造相同。
**Food List (not converted from txt, working)**
[["Liver" , 253, 0],["Spinach" , 844, 45],["Sausage" , 200, 100]]
**Food List printed once split from .txt file**
[['Liver , 253, 0', ''], ['Spinach, 844, 45', ''], ['Sausage, 200, 100', ''], ['']]
有人可以用简单的语言向我解释我在这里做错了什么,以及如何解决这个问题?这将不胜感激。此外,空元素来自哪里,以及如何摆脱它们?
答案 0 :(得分:2)
首先使用":\n"
剥离str.rstrip
,然后将行拆分为', '
:
演示:
>>> strs = "Liver , 253, 0:\n"
>>> strs.rstrip(':\n').split(', ')
['Liver ', '253', '0']
代码:
#use `with` statement for handling file, it will close the file for you.
>>> with open('nutrientlist.txt') as f:
... foodlist = []
... for line in f:
if line.strip(): #check if the line is empty or not
spl = line.rstrip(':\n').split(', ')
spl[1:] = [int(x) for x in spl[1:]] # apply `int()` to all items except first one
... foodlist.append(spl) #append the list to foodlist
...
>>> foodlist
[['Liver ', 253, 0], ['Spinach', 844, 45], ['Sausage', 200, 100]]
代码的工作版本:
f = open('abc') # Never use `list` as a variable name
data = f.read()
split = data.split("\n")
foodList = []
for x in split:
if x.strip(): #check if the line is empty or not
foodList.append( x.rstrip(':').split(', ') )
f.close()
print foodList