RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 555969
Accepted
Robert
Robert
Asked:2020-08-16 20:52:23 +0000 UTC2020-08-16 20:52:23 +0000 UTC 2020-08-16 20:52:23 +0000 UTC

逐字符拆分列表元素

  • 772

你好!

请告诉我,我怎样才能['1', '22', '333']按字符拆分捕获列表,即 列一个清单['1', '2', '2', '3', '3', '3']

提前致谢!

python
  • 8 8 个回答
  • 10 Views

8 个回答

  • Voted
  1. Best Answer
    FeroxTL
    2020-08-16T21:01:51Z2020-08-16T21:01:51Z

    在一行中的功能:

    reduce(lambda a, x: a + x, map(lambda x: list(x), ['1', '22', '333']))
    

    我解释一下 -reduce它以一个函数作为输入,该函数组合了按函数拆分列表的结果map。Map接受一个函数和一个初始数组作为输入,这个函数在数组的每个元素上执行。同样可以用下面的代码来表达:

    >>> result_list = []
    >>> for x in ['1', '22', '333']:
    ...     for y in list(x):
    ...         result_list.append(y)
    ... 
    >>> print(result_list)
    ['1', '2', '2', '3', '3', '3']
    

    建议选项的速度比较:

    join在一行结果中使用和关联的变体已经完成了所有工作。这并不奇怪 - 这里的所有操作都很快。适用于任何iterable对象:

    $python3 -m timeit "list(''.join(['1', '22', '333']))"
    1000000 loops, best of 3: 0.318 usec per loop
    

    使用@jfs 答案中的列表生成器的变体非常快:

    $python3 -m timeit "[char for s in ['1', '22', '333'] for char in s]"
    1000000 loops, best of 3: 0.452 usec per loop
    

    use 选项sum在速度上排名第三,但在我看来它失去了直观性:

    $python3 -m timeit "sum([list(i) for i in ['1', '22', '333']], [])"
    1000000 loops, best of 3: 0.984 usec per loop
    

    选项开map-reduce是最慢的。我为什么要用它?因为我喜欢调用链。剩下的就是味道了。然而,即使是 Guido 也讨厌reduce(并functools在python3中呈现)

    $python3 -m timeit "from functools import reduce; reduce(lambda a, x: a + x, map(lambda x: list(x), ['1', '22', '333']))"
    100000 loops, best of 3: 2.16 usec per loop
    

    选项 ccollections涵盖了传递的对象可以是不可迭代的(例如,一个数字)的所有情况,但这样做的代价是执行时间很长:

    $python3 -m timeit "import collections
    
    def it(obj):
        if isinstance(obj, collections.Iterable):
            for ob in obj:
                if isinstance(ob, collections.Iterable) and len(ob) > 1:
                    yield from it(ob)
                else: yield ob
        else:
            yield obj
    
    list(it(['1', 2, [2, 44, '123', ('qwe')], 2]))"
    100000 loops, best of 3: 14.6 usec per loop
    
    • 17
  2. andreymal
    2020-08-16T21:23:11Z2020-08-16T21:23:11Z

    由于他们开始在这里收集不同的方式,我将提供:

    list(''.join(['1', '22', '333']))
    

    (现在有人必须比较所有选项的性能:)

    • 12
  3. privod
    2020-08-16T21:05:19Z2020-08-16T21:05:19Z

    你可以这样做:

    l = ['1', '22', '333']
    s = sum([list(i) for i in l], [])
    print(s)
    ['1', '2', '2', '3', '3', '3']
    
    • 10
  4. jfs
    2020-08-16T22:09:32Z2020-08-16T22:09:32Z

    要从字符串列表中获取字符列表,可以在列表生成器中使用嵌套循环:

    strings = ['1', '22', '333']
    chars = [char for s in strings for char in s]
    # chars -> ['1', '2', '2', '3', '3', '3']
    

    类似问题:Flattening a shallow list in Python。

    根据@Alex Martelli 的说法,此选项可能比使用sum(),reduce()的解决方案更快。列表理解解决方案也比reduce().

    • 10
  5. vadim vaduxa
    2020-08-16T21:04:36Z2020-08-16T21:04:36Z
    import collections
    
    def it(obj):
        if isinstance(obj, collections.Iterable):
            for ob in obj:
                if isinstance(ob, collections.Iterable) and len(ob) > 1:
                    yield from it(ob)
                else: yield ob
        else:
            yield obj
    
    a = list(it(['1', 2, [2, 44, '123', ('qwe')], 2]))
    print(a)
    ['1', 2, 2, 44, '1', '2', '3', 'q', 'w', 'e', 2]
    
    • 6
  6. Max
    2020-08-16T22:01:09Z2020-08-16T22:01:09Z

    抓住:

    a = ['1', '22', '333']
    a = [x for x in ''.join(a)]
    
    • 4
  7. vadim vaduxa
    2020-08-17T02:14:35Z2020-08-17T02:14:35Z
    import time
    from functools import wraps, reduce
    
    def tefn(fn, args, kwargs):
        t = time.time()
        tuple(fn(*args, **kwargs))
        return t - time.time()
    
    def efn(fn, args, kwargs):
        t = time.time()
        fn(*args, **kwargs)
        return t - time.time()
    
    def runTime(tp=0, count=25):
        def dec(fn):
            @wraps(fn)
            def wrap(*args, **kwargs):
                print(fn)
                res = tefn if tp else efn
                return sum(res(fn, args, kwargs) for _ in range(count)) / count
            return wrap
        return dec
    
    
    @runTime()
    def fnTuple(): return tuple(char for s in list_ for char in s)
    @runTime(tp=1)
    def fnIter(): return iter(char for s in list_ for char in s)
    @runTime()
    def fnList(): return list(char for s in list_ for char in s)
    @runTime(tp=1)
    def fnYield():
        for a in list_: yield from a
    @runTime(tp=1)
    def fnJoin(): return ''.join(list_)
    @runTime()
    def fnSumm(): return sum([list(i) for i in list_], [])
    @runTime()
    def fnReduce(): return reduce(lambda a, x: a + x, map(lambda x: list(x), list_))
    @runTime()
    def fnNew(): return ['1' * 999, '22' * 999, '333' * 999] * 99
    
    if __name__ == '__main__':
        list_ = ['1' * 999, '22' * 999, '333' * 999] * 99
        g = globals()
        result = list((fn.__name__, fn()) for fn in (g[f] for f in g if f.startswith('fn')))
        result.sort(key=lambda r: r[1], reverse=True)
        for e, r in enumerate(result):
            print(e, r)
    

    出去:

    <function fnReduce at 0x02938FA8>
    <function fnNew at 0x0293B078>
    <function fnList at 0x02938D68>
    <function fnTuple at 0x028F7348>
    <function fnYield at 0x02938DF8>
    <function fnIter at 0x02938CD8>
    <function fnJoin at 0x02938E88>
    <function fnSumm at 0x02938F18>
    0 ('fnNew', 0.0)
    1 ('fnJoin', -0.018803834915161133)
    2 ('fnYield', -0.04936907768249512)
    3 ('fnTuple', -0.061401805877685546)
    4 ('fnList', -0.06224835395812988)
    5 ('fnIter', -0.07298644065856934)
    6 ('fnSumm', -0.8121062469482422)
    7 ('fnReduce', -0.8314747619628906)
    
    • 3
  8. mr.polden2010
    2021-12-20T03:35:40Z2021-12-20T03:35:40Z

    或者

    import pandas as pd
    a = ['1', 2, [2, 44, '123', ('qwe')], 2]
    
    df = pd.DataFrame(a, columns=['a'])
    a = list(''.join(map(str, df.explode('a')['a'])))
    
    • 1

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    如何停止编写糟糕的代码?

    • 3 个回答
  • Marko Smith

    onCreateView 方法重构

    • 1 个回答
  • Marko Smith

    通用还是非通用

    • 2 个回答
  • Marko Smith

    如何访问 jQuery 中的列

    • 1 个回答
  • Marko Smith

    *.tga 文件的组重命名(3620 个)

    • 1 个回答
  • Marko Smith

    内存分配列表C#

    • 1 个回答
  • Marko Smith

    常规赛适度贪婪

    • 1 个回答
  • Marko Smith

    如何制作自己的自动完成/自动更正?

    • 1 个回答
  • Marko Smith

    选择斐波那契数列

    • 2 个回答
  • Marko Smith

    所有 API 版本中的通用权限代码

    • 2 个回答
  • Martin Hope
    jfs *(星号)和 ** 双星号在 Python 中是什么意思? 2020-11-23 05:07:40 +0000 UTC
  • Martin Hope
    hwak 哪个孩子调用了父母的静态方法?还是不可能完成的任务? 2020-11-18 16:30:55 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    user207618 Codegolf——组合选择算法的实现 2020-10-23 18:46:29 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    Arch ArrayList 与 LinkedList 的区别? 2020-09-20 02:42:49 +0000 UTC
  • Martin Hope
    iluxa1810 哪个更正确使用:if () 或 try-catch? 2020-08-23 18:56:13 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5