【问题标题】:Python list buildingPython列表构建
【发布时间】:2012-11-13 05:01:47
【问题描述】:

我必须从一个 .txt 文件为购物清单构建一个函数,如下所示:

milk
cheese

bread
hotdog buns

chicken
tuna
burgers

等等。从上面的列表中,我的购物清单应该看起来像 [['milk', 'cheese'], ['bread', 'hotdog buns'], ['chicken', 'tuna', 'burgers']],因此是一个列表列表,其中的项目在文本文件中存在空格时被分隔。

我必须使用.readline(),而我不能使用.readlines(), .read(),或for 循环。我的代码现在创建了一个空列表:

def grocery_list(foods):
    L = open(foods, 'r')
    food = []
    sublist = []
    while L.readline() != '':
        if L.readline() != '\n':
            sublist.append(L.readline().rstrip('\n'))
        elif L.readline() == '\n':
            food.append(sublist)
            sublist = []
    return food

我不知道哪里出错了,所以它返回一个完全空的列表。我也不确定'''\n' 部分;我正在使用的示例测试文件在 shell 中打开时如下所示:

milk\n
cheese\n
\n
...
''
''

但是.rstrip() 或整个!= '' 对每个列表都有意义吗?还是我只是没有走在正确的轨道上?

【问题讨论】:

  • 我必须使用 .readline(),而不能使用 .readlines()、.read() 或 for 循环。 为什么会这样?

标签: python python-3.x


【解决方案1】:

一个问题是您没有将最终的sublist 添加到结果中。正如@Xymotech 提到的,您需要捕获每次调用readline() 的结果,因为下一次调用会有所不同。以下是我将如何修改您的代码。

def grocery_list(foods):
    with open(foods, 'r') as L:        
        food = []            
        sublist = []            

        while True:
            line = L.readline()
            if len(line) == 0:
                break

            #remove the trailing \n or \r
            line = line.rstrip()

            if len(line) == 0:
                food.append(sublist)
                sublist = []                    
            else:
                sublist.append(line)
        if len(sublist) > 0:
            food.append(sublist)

        return food

注意with语句的使用。这可确保文件在不再需要后关闭。

【讨论】:

    【解决方案2】:

    我已将您的代码修改如下,以实现您想要的:

    def grocery_list(foods):
        with open(foods,'r') as f:
            food=[]
            sublist=[]
            while True:
                line=f.readline()
                if len(line)==0:
                    break
                if line !='\n':
                    sublist.append(line.strip())
                else:
                    food.append(sublist)
                    sublist=[]
            food.append(sublist)
        return food
    

    【讨论】:

      【解决方案3】:

      在我看来,更整洁一些。实现所需结果的另一种选择。

      def grocerylist(foods):  
        with open(foods) as f:
          line = f.readline()
          items = []
          while line:
            items.append(line.rstrip())
            line = f.readline()
          newlist = [[]]
          for item in a:
            if not x: newlist.append([])
            else: newlist[-1].append(x)
          return newlist
      

      newlist 现在包含以下内容:

      [['milk', 'cheese'], ['bread', 'hotdog buns'], ['chicken', 'tuna', 'burgers']]
      

      【讨论】:

        【解决方案4】:

        每次你调用 L.readline() 时,你都在读另一行。您应该第一次存储它的值,并在接下来的每个语句中使用该值。

        【讨论】:

        • L = open(foods, 'r') food = [] sublist = [] item = L.readline() while item != '': if item != '\n': sublist .append(item.rstrip('\n')) elif item == '\n': food.append(sublist) sublist = [] 返回食物,它做同样的事情(空列表)。是这个意思吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 2015-09-25
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多