【问题标题】:how do you split elements of a list of list in python?你如何在python中拆分列表列表的元素?
【发布时间】:2014-03-28 23:34:59
【问题描述】:

所以我有一个如下所示的文本文件:

abcd 
efghij
klm

我需要将其转换为二维列表。它应该是这样的:

[['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h', 'i', 'j'],
['k', 'l', 'm']]

到目前为止,我已经设法得到了这个结果:

[["abcd"], ["efghij"], ["klm"]]

谁能帮我弄清楚下一步应该是什么? 到目前为止,这是我的代码:

def readMaze(filename):
    with open(filename) as textfile:
        global mazeList
        mazeList = [line.split() for line in textfile]
        print mazeList

【问题讨论】:

    标签: python list split strip


    【解决方案1】:

    str.split() 在空白处拆分。 str.split('') 分别拆分每个字符。(显然我记错了,str.split('')"empty separator" 抛出了一个ValueError

    您只需从中构建一个list

    text = """abcd
    efghij
    klm"""
    
    mazelist = [list(line) for line in text.splitlines()]
    # the splitlines call just makes it work since it's a string not a file
    print(mazelist)
    # [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm']]
    

    【讨论】:

    • 它给了我一个属性错误 - 文件对象没有属性'splitlines'。有什么建议吗?
    • @user3213742 正如我在该行下方的评论中提到的那样,我只使用了splitlines,因为我将您的文本放入字符串而不是对象中............文件不要'没有splitlines 方法,字符串有。
    【解决方案2】:

    列出文件中的每一行:

    with open('tmp.txt') as f:
        z = [list(thing.strip()) for thing in f]
    

    【讨论】:

      【解决方案3】:

      如上所述,您只需要从字符串构建一个列表。

      假设字符串保存在 some_text 中;

      lines = some_text.split('\n')
      my_list = []
      for line in lines:
          line_split = list(line)
          my_list.append(line_split)
      

      单线;

      my_list = map(lambda item: list(item), some_text.split('\n'))
      

      应该可以解决问题。

      【讨论】:

      • with open('file.txt') as f: , z = map(list, map(str.strip,f)) , - 使用 map() 可能会更好。
      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 2017-03-14
      • 2014-06-02
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多