【问题标题】:How to take multiple lists and nest them?如何获取多个列表并嵌套它们?
【发布时间】:2014-09-10 22:23:56
【问题描述】:

目前正在处理一个读入 python 的文本文件,然后必须将其制成带有列表的列表(我猜是嵌套的?)到目前为止,我已经尝试过双重拆分文件但无济于事。这是阅读器代码的样子:

def populationreader():
    with open("PopulationofAnnecy", "r") as in_file:
        for lines in in_file:
            Nested = lines.split(',')
            print Nested

由此我得到结果:

['State', ' Total #', '% passed', '%female\n']
['Alabama', '126', '79', '17\n']
['Alaska', '21', '100', '10\n']
['Arizona', '190', '59', '16\n']
['Arkansas', '172', '49', '28\n']
etc...

我将如何删除第一行,摆脱 \n 并嵌套列表,使它们看起来更像这样:

[[“Alabama”, 126, 79, 17], [“Alaska”, 21, 100, 10] …. ]

【问题讨论】:

    标签: python list python-2.7 nested-lists


    【解决方案1】:

    首先,您必须声明要在其中存储元素的列表:

    result = []
    

    那么,由于lines.split(',') 将返回一个字符串 列表,因此您必须将它们转换为整数。为此,您可以将列表的元素分配给单独的变量:

    a,b,c,d = lines.split(',')
    

    然后转换你想要的,并将它们作为列表附加到result

    result.append([a, int(b), int(c), int(d)])
    

    【讨论】:

      【解决方案2】:

      在拆分之前strip

      def populationreader():
          with open("PopulationofAnnecy", "r") as in_file:
              for lines in in_file:
                  Nested = lines.strip().split(',')
      
                  print Nested
      

      制作可以使用的整数

      [int(i) if i.isdigit() else i for i in nested]
      

      【讨论】:

      • 谢谢!这几乎正​​是我想要的:)
      【解决方案3】:

      您可以使用列表推导来创建嵌套列表:

      def populationreader():
          with open("PopulationofAnnecy", "r") as in_file:
              nested = [line.strip().split(',') for line in in_file][1:]
      

      【讨论】:

        【解决方案4】:

        1.使用条带删除\n

        2. 使用 append 将单独的行添加到结果列表中;从索引 1 开始跳过第一行。

            def populationreader():
                Nested = []
                with open("PopulationofAnnecy", "r") as in_file:
                    for lines in in_file[1:]:
                        Nested.append(lines.split(',').strip())
                print Nested
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-02-22
          • 1970-01-01
          • 2022-01-24
          • 1970-01-01
          • 2014-04-20
          • 2018-07-16
          • 1970-01-01
          相关资源
          最近更新 更多