我想创建一个由不带空格的 split() 序列产生的值的字典。
如果我有一个格式如下的字符串列表:
lines = ['Item1 = A Item2 = B Item3 = C',
'Item4 = D Item5 = E']
我知道如何通过空格获取对>2 通过:
s = [y for x in lines for y in x.split(' ') if y]
这将返回另一个包含对的字符串列表:
s = ['Item1 = A', 'Item2 = B', 'Item3 = C', 'Item4 = D', 'Item5 = E']
到目前为止一切顺利。现在,我需要用 =
打破对,左边是 key
,右边是 value
。我可以通过以下方式做到这一点:
t = [y.split('=') for x in lines for y in x.split(' ') if y]
这将返回另一个包含破损对的字符串列表:
t = ['Item1', 'A', 'Item2', 'B', 'Item3', 'C', 'Item4', 'D', 'Item5', 'E']
现在每个项目都有一个尾随或前导空格。这很容易通过将最后一个列表理解行更新为:
t = [z.strip() for x in lines for y in x.split(' ') for z in y.split('=') if y]
为了使它成为我知道调用生成器表达式的字典:
d = dict(y.split('=') for x in lines for y in x.split(' ') if y)
但这会保留尾随或前导空格以及 key
和 value
。如果我要添加 z.strip()
我会得到错误:
ValueError:字典更新序列元素 #0 的长度为 5; 2 是必需的
问题:
How can I use the
dict()
generator andstrip()
whitespace from thesplit('=')
call at the same time? Or am I forced tostrip()
after thedict()
call?
最佳答案
这个怎么样:
s = ['Item1 = A', 'Item2 = B', 'Item3 = C', 'Item4 = D', 'Item5 = E']
#b = dict([x.split(' = ') for x in s]) # list comprehension: slightly faster.
b = dict(x.split(' = ') for x in s) # generator expr. : memory efficient.
print(b) # {'Item3': 'C', 'Item1': 'A', 'Item4': 'D', 'Item5': 'E', 'Item2': 'B'}
关于python - 调用 strip() 后将 split() 转换为 dict(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45547263/