【问题标题】:Flattening nested list of strings into a single list of ints [closed]将嵌套的字符串列表展平为单个整数列表[关闭]
【发布时间】:2013-05-10 14:41:17
【问题描述】:

今天下午我很无聊。如何转换

['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']

进入

[1,9,3,10,5,8,8,11,2,7,4,5,2,6]

?

【问题讨论】:

    标签: python list python-3.x


    【解决方案1】:
    >>> L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']
    >>> [int(y) for x in L for y in x.split(',')]
    [1, 9, 3, 10, 5, 8, 8, 11, 2, 7, 4, 5, 2, 6]
    

    这个嵌套列表推导等效于这个:

    res = []
    for x in L:
        for y in x.split(','):
            res.append(int(y))
    

    如你所见,自上而下的结构在列表推导中是从左到右的

    即。

    [int(y) 
     for x in L 
     for y in x.split(',')]
    

    现在解开的看起来与for 循环相同。


    另一种方式:

    >>> [int(x) for x in ','.join(L).split(',')]
    [1, 9, 3, 10, 5, 8, 8, 11, 2, 7, 4, 5, 2, 6]
    

    【讨论】:

    • 完美运行,谢谢。我不确定我是否完全理解逻辑。如果您有时间,我将不胜感激。
    • @user1478335 我也添加了:)
    【解决方案2】:

    鉴于有几种不同的方法可以做到这一点,我决定运行一些(快速)测试,看看哪种方法最快。

    python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "[int(x) for x in ''.join(L).split(',')]"
    >>> 100000 loops, best of 3: 3.2 usec per loop
    
    python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "[int(y) for x in L for y in x.split(',')]"
    >>> 100000 loops, best of 3: 6.38 usec per loop
    
    python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6'];from itertools import chain" "[int(x) for x in chain.from_iterable(l) if x != ',']"
    >>> 100000 loops, best of 3: 6.68 usec per loop
    

    好像[int(x) for x in ''.join(L).split(',')]拿了蛋糕。

    编辑:按照 jamylak 的建议,我添加了以下测试:

    python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "map(int, ''.join(L).split(','))"
    >>> 100000 loops, best of 3: 2.79 usec per loop
    
    python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "list(map(int, ''.join(L).split(',')))"
    >>> 100000 loops, best of 3: 3.02 usec per loop
    

    所以map(int, ''.join(L).split(','))list(map(int, ''.join(L).split(','))) for python3 是最好的方法。

    【讨论】:

    • 最快的可能是 Py2 上的 map(int, ''.join(L).split(',')),即 Py 3 上的 list(map(int, ''.join(L).split(',')))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2014-02-16
    • 2020-07-12
    • 2013-11-13
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多