gpt4 book ai didi

python - 如何从列表创建字典

转载 作者:行者123 更新时间:2023-11-30 22:05:23 26 4
gpt4 key购买 nike

我有一个句子列表,我想将其转换为仅包含用户名和年龄的词典。

list=['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']

我想要得到的输出是像这样的字典

dic={David:27,John:99,rain:45}

感谢您的帮助

最佳答案

您可以定义一个自定义函数,通过map将其应用到每个字符串,然后输入到dict:

L = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']

def key_value_extractor(x):
x_split = x.split(',') # split by ','
name = x_split[0][1:] # take 1st split and exclude first character
age = int(x_split[1].rsplit(maxsplit=1)[-1]) # take 2nd, right-split, convert to int
return name, age

res = dict(map(key_value_extractor, L))

{'David': 27, 'John': 99, 'rain': 45}

关于python - 如何从列表创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com