如何在列表中拆分字符串以在 Python 中创建键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12739911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:45:45  来源:igfitidea点击:

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

pythonstring

提问by Vor

I have a list that looks like this:

我有一个看起来像这样的列表:

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

And I want to split this list by '=' so that everything on the left side will become keys and on the right, values.

我想用 '=' 分割这个列表,这样左侧的所有内容都将成为键,而右侧的所有内容都将成为值。

{ 
    'abc':'lalalla',
    'appa':'kdkdkdkd',
    'kkakaka':'oeoeo'
}

采纳答案by Demian Brecht

a = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
d = dict(s.split('=') for s in a)
print d


Output:
{'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'}

http://codepad.org/bZ8lGuHE

http://codepad.org/bZ8lGuHE

回答by Joran Beasley

print dict([s.split("=") for s in my_list])

like this

像这样

>>> my_list = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
>>> print dict(s.split("=") for s in my_list) #thanks gribbler
{'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'}

回答by user117529

In addition, make sure you limit the splits to 1, in case the right-hand side contains an '='.

此外,确保将拆分限制为 1,以防右侧包含“=”。

d = dict(s.split('=',1) for s in a)

回答by jpp

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

您可以将map对象直接提供给dict. 对于没有参数的内置函数,map应该表现出相似或更好的性能。引入参数时,您会看到性能下降:

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

回答by Vlad Bezden

Example by using mapfunction

使用map函数的示例

a = ["abc=lalalla", "appa=kdkdkdkd", "kkakaka=oeoeoeo"]
d = dict(map(lambda s: s.split('='), a))