返回一个清单

时间:2012-11-14 18:11:55

标签: python file list nested

我有关于返回以下功能的问题 给我一个带有食物清单的文件,看起来像这样:

'''
bread
bun

milk
soya milk
'''

我必须返回食物清单列表,例如[['bread','bun'], ['milk','soya milk']]

我是python和编程的新手,因此我被困在for循环中以创建我的列表。任何输入将不胜感激 - kev

7 个答案:

答案 0 :(得分:2)

有效......

grocery_list_file = open('foods.txt','r').read()
foods = grocery_list_file.split("\n\n") #split on blank lines

result = []
for food in foods:
   newFood = food.split("\n") # split the lines, creating the output...
   result += [newFood]
return result

在一行中:

print [f.strip().split("\n") for f in open('foods.txt','r').read().split("\n\n")]

答案 1 :(得分:0)

非常接近。当next_food为空且非空白时,您应该使用if并处理这两种情况,而不是使用while len(next_food) > 0:。就像您的评论所指出的那样,在返回之前,您应该包括最后一个子列表。

另一个需要检查的事情是next_food是否在最后包含换行符。如果它在那里你应该去除换行符。最后,还有一个替代if len(next_food):的快捷方式。只需写if next_food:即可。

答案 2 :(得分:0)

您希望在到达新类别时附加子列表,然后启动新的子列表。当到达文件末尾时,将剩余的sub_list附加到末尾非常重要。

new_list.append("\n")   #to make sure it appends the last category
for next_food in new_list:
        if next_food = "\n":
            result.append(sub_list)
            sub_list = []
        else:
            sub_list.append(next_food)

答案 3 :(得分:0)

这不是一个很好的解决方案......但它有一些有趣的技巧..

>>> s = '''
... bread
... bun
...
... milk
... soya milk
... '''
>>> import re
>>> parts = re.sub("[\[\]']","",str(s.strip().splitlines())).split(", ,")
>>> import string
>>> print [map(string.strip,p.split(",")) for p in parts]
[['bread', 'bun'], ['milk', 'soya milk']]

答案 4 :(得分:0)

使用itertools.groupby

from itertools import groupby


def build_grocery_list():
    # using "with" to open the file - recommended way
    with open("foods.txt") as f:
        # lines will contain all the lines in the file, without "\n" characters
        lines = f.read().splitlines()

        # initialize result as an empty list
        result = []

        # Now for the fun part: group file lines basing on whether they are empty
        # (bool(string) is analogous to as using "if string:" -- will be True if
        #  the string is not empty)
        #
        # groupby works in such a way that it appends stuff to the group as long
        # as "key" condition is the same, returning (key, group) pairs.
        #
        # So, we get pairs: (bool(string), string-group) where:
        # - bool(string) is the group "key", delimiting empty and non-empty
        #   strings
        # - string-group is a lazy *generator*, hence the "list(group)"
        for nonblank, group in groupby(lines, bool):
            if nonblank:
                result.append(list(group))

    return result

如果你正在学习Python,我真的建议你熟悉优秀的itertools模块 - 它非常方便!

答案 5 :(得分:0)

最简单易读的方法是:

>>> [el.strip().split('\n') for el in text.split('\n\n')]
[['bread', 'bun'], ['milk', 'soya milk']]
  1. \n\n拆分会产生一条线,紧接着是一个空行

  2. .strip()删除了前导和尾随换行符,因此只有换行符 元素在那里

  3. split然后将这些元素分解为一个列表,从而生成列表列表

  4. 或者,您可以使用itertools.groupby

    >>> [groups for groups in (list(g) for k, g in groupby(text.splitlines(), bool)) if groups[0]]
    [['bread', 'bun'], ['milk', 'soya milk']]
    

答案 6 :(得分:0)

如果输入文件小到可以完全读入内存,我会这样做:

with open('grocery_list.txt', 'rt') as grocery_list_file:
    data = grocery_list_file.read()

sublist = [item.strip().split('\n') for item in data.split('\n\n')]

输出:

sublist: [['bread', 'bun'], ['milk', 'soya milk']]