我有一个列表 ['111,"A","yes"','112,"B","no"','113,C,"maybe"']
我希望输出为 {111:('A',"yes"),112:('B',"no"),113:('C',"maybe")]}
我尝试遍历列表,然后遍历字符串,但最终遍历了 1,1,1 而不是 111 作为一个完整数字。
最佳答案
使用str.split()
:
In [1]: lst = ['111,"A","yes"','112,"B","no"','113,C,"maybe"']
In [2]: dict((int(s[0]), s[1].split(',')) for s in (grp.split(',', 1)
for grp in lst))
Out[2]: {111: ['"A"', '"yes"'],
112: ['"B"', '"no"'],
113: ['C', '"maybe"']}
关于python - 从列表中的字符串创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420953/