python - 调用 strip() 后将 split() 转换为 dict()

标签 python python-3.x

我想创建一个由不带空格的 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)

但这会保留尾随或前导空格以及 keyvalue。如果我要添加 z.strip() 我会得到错误:

ValueError:字典更新序列元素 #0 的长度为 5; 2 是必需的

问题:

How can I use the dict() generator and strip() whitespace from the split('=') call at the same time? Or am I forced to strip() after the dict() 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/

相关文章:

python - 类型错误 : replace() takes no keyword arguments when we use (old ='XYZ' , 新 ='ABC' )

python - connection.commit() 性能影响

python - 如何选择过滤器选择列表中的列列表

Python 代码在 2.7 中编译,而不是在 3.2 中编译

python-3.x - 在OpenCV中播放电影

python-3.x - python : Clustering Search Keywords

python - 使用 Python 填写 Web 表单

python - 加载 JSON 并获取某些数据 (Python)

python - 如何使用 pip 搜索可用的 Python 包?

python - 使用正则表达式提取特定行下方的行上的数字?