Tom*_*kov 4 python dictionary list type-conversion python-3.x
假设我有一个以字符串和整数作为值的字典混合列表,并且我想将整数转换为字符串,考虑到该列表是流动的、长的和复杂的,应该如何做到这一点,而不需要遍历所有地方并将它们一一转换还可能将一些现有值更改为整数。
例子:
list = [{'a':'p', 'b':2, 'c':'k'},
{'a':'e', 'b':'f', 'c':5}]
Run Code Online (Sandbox Code Playgroud)
现在,如果我尝试用字符串打印列表的值,则会出现如下错误。
例子:
for x in list:
print('the values of b are: '+x['b'])
Run Code Online (Sandbox Code Playgroud)
输出:
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助,谢谢!
解决方案
list = [{'a':'p', 'b':2, 'c':'k'},
{'a':'e', 'b':'f', 'c':5}]
for dicts in list:
for keys in dicts:
dicts[keys] = str(dicts[keys])
print('the values of b are: '+ dicts["b"])
Run Code Online (Sandbox Code Playgroud)
小智 5
也许这个:
list = [
{'a':'p', 'b':2, 'c':'k'},
{'a':'e', 'b':'f', 'c':5}
]
list = [{key: str(val) for key, val in dict.items()} for dict in list]
print(list)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15167 次 |
| 最近记录: |