在Python中,如何从文件创建列表?

时间:2015-12-14 05:03:40

标签: python list file

我正在尝试创建一个列表,其中文件的每一行都是该行中单词的列表。例如,如果文件读取:

apples oranges bananas

kale spinach

carrots tomatoes celery broccoli

然后我想要列表阅读:

l = [[["apples"], ["oranges"], ["bananas"]], [["kale"], ["spinach"]], [["carrots"], ["tomatoes"], ["celery"], ["broccoli"]]]

最好的方法是什么? readlines方法?

3 个答案:

答案 0 :(得分:2)

你可能会这样做..

with open(file) as f:
    print [[[j] for j in i.split()] for i in f if i]

示例:

>>> s = '''apples oranges bananas

kale spinach

carrots tomatoes celery broccoli'''.splitlines()
>>> [[[j] for j in i.split()] for i in s if i]
[[['apples'], ['oranges'], ['bananas']], [['kale'], ['spinach']], [['carrots'], ['tomatoes'], ['celery'], ['broccoli']]]

答案 1 :(得分:0)

你可以这样做:

L = []
with open('words.txt','r') as f:
    for line in f:
        L.append(line.split())

答案 2 :(得分:0)

当我试图向@AvinashRaj解释时,你需要使用类似的东西  not i.isspace()过滤掉空行(因为它们仍然包含换行符)

with open(file) as fin:
    print [[[j] for j in i.split()] for i in fin if not i.isspace()]

with块称为上下文管理器。一旦到达块的末尾,它就会关闭fin