1

我正在玩列表,并试图提出一个包含来自不同食物条目的营养成分的列表。

所以我基本上想像这样一次访问一列:

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', ''], ['']]

有人可以简单地向我解释我在这里做错了什么,以及如何解决它?这将不胜感激。另外,空元素是从哪里来的,我该如何摆脱它们?

4

1 回答 1

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
于 2013-06-23T13:59:57.240 回答