【问题标题】:Convert one dimension list to two diminsions with specific delimiters将一维列表转换为具有特定分隔符的二维列表
【发布时间】:2014-11-25 14:38:36
【问题描述】:

我有一个类似的列表:

['A;B;C;D\nE;F;G;H\nI;J;K;L\n']

我想创建一个包含二维数据的新列表,例如:

[[A,B,C,D],[E,F,G,H],[I,J,K,L]]

我怎样才能使“;”作为分隔符和“\n”将数据输入新行?

谢谢。

(我使用的是python v3)

【问题讨论】:

    标签: python string list python-3.x delimiter


    【解决方案1】:

    listcomprehensionstr.split()str.strip() 一起使用

    a = ['A;B;C;D\nE;F;G;H\nI;J;K;L\n']
    In [152]: [x.split(';') for x in a[0].strip().split('\n')]
    Out[152]: [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']]
    

    或将maplambda 函数一起使用

    In [160]: map(lambda x: x.split(';') ,a[0].strip().split('\n'))
    Out[160]: [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']]
    

    两者时差很小

    In [162]: %timeit map(lambda x: x.split(';') ,a[0].strip().split('\n'))
    100000 loops, best of 3: 2.04 µs per loop
    
    In [161]: %timeit [x.split(';') for x in a[0].strip().split('\n')]
    1000000 loops, best of 3: 1.46 µs per loop
    

    【讨论】:

    • @pafpaf 请检查解决方案
    猜你喜欢
    • 2021-12-18
    • 2022-12-29
    • 2023-03-27
    • 2015-02-06
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2022-01-15
    相关资源
    最近更新 更多