How to split a string within a list to create key-value pairs in Python

后端 未结 5 1705
灰色年华
灰色年华 2020-12-01 14:07

I have a list that looks like this:

[ \'abc=lalalla\', \'appa=kdkdkdkd\', \'kkakaka=oeoeoeo\']

And I want to split this list by \'=\' so th

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 14:54

    You can feed a map object directly to dict. For built-in functions without arguments, map should show similar or better performance. You will see a drop-off in performance when introducing arguments:

    from functools import partial
    
    L = ['abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
    L2 = ['abc lalalla', 'appa kdkdkdkd', 'kkakaka oeoeoeo']
    
    n = 100000
    L = L*n
    L2 = L2*n
    
    %timeit dict(map(partial(str.split, sep='='), L))  # 234 ms per loop
    %timeit dict(s.split('=') for s in L)              # 164 ms per loop
    
    %timeit dict(map(str.split, L2))                   # 141 ms per loop
    %timeit dict(s.split() for s in L2)                # 144 ms per loop
    

提交回复
热议问题