This question already has answers here:
How to split a string within a list to create key-value pairs in Python

(5个答案)


3年前关闭。




请考虑以下字典理解:
foo = ['super capital=BLUE', 'super foo=RED']
patternMap = {x.split("=")[0]:x.split("=")[1] for x in foo}

这很简洁,但是我不喜欢需要两次调用x.split('=')的事实。我尝试了以下操作,但它只会导致语法错误。
patternMap = {y[0] : y[1] for y in x.split('=') for x in foo}

是否有一种“正确的”方法来获得前两行的结果,而不必两次调用x.split()或更冗长?

最佳答案

直接使用类似元组的dict:

代码:

patternMap = dict(x.split('=') for x in foo)

测试代码:
foo = ['super capital=BLUE', 'super foo=RED']
patternMap = {x.split("=")[0]: x.split("=")[1] for x in foo}
print(patternMap)

patternMap = dict(x.split('=') for x in foo)
print(patternMap)

# or if you really need a longer way
patternMap = {y[0]: y[1] for y in (x.split('=') for x in foo)}
print(patternMap)

结果:
{'super capital': 'BLUE', 'super foo': 'RED'}
{'super capital': 'BLUE', 'super foo': 'RED'}
{'super capital': 'BLUE', 'super foo': 'RED'}

关于python - 是否可以从未解析的字符串列表构造字典理解而无需双重拆分?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49001176/

10-09 21:06