2024-09-29 02:16:11 发布
网友
我这里有一本字典:
dict = {'AB': 1, 'AE': '0', 'CC': '3'}
我正试图将字典转换成精确的字符串格式:
AB1,AE0,CC3
我目前正在尝试:
string = ",".join(("{},{}".format(*i) for i in dict.items()))
但我的成果是:
AB,1,AE,0,CC,3
只差一点点。你知道吗
有人知道如何将这本词典正确地格式化成字符串吗?你知道吗
谢谢
代码:
dict = {'AB': 1, 'AE': '0', 'CC': '3'} string=','.join([i+str(dict[i]) for i in dict]) print(string)
输出:
好了(删除逗号):
d = {'AB': 1, 'AE': '0', 'CC': '3'} output = ",".join(["{}{}".format(key, value) for key, value in d.items()]) # ^^^^ print(output)
这就产生了
或者使用原始的拆包方法:
output = ",".join(["{}{}".format(*x) for x in d.items()])
另外,请不要以内置对象(dict、list、tuple等)命名变量。你知道吗
如果您使用的是Python 3,则可以使用所谓的f字符串:
d = {'AB': 1, 'AE': '0', 'CC': '3'} out = ','.join([f'{i}{d[i]}' for i in d.keys()]) print(out)
如果您想了解更多关于f字符串的信息,请参见tutorial。请记住,此解决方案仅适用于Python3.3及更新版本。你知道吗
代码:
输出:
好了(删除逗号):
这就产生了
或者使用原始的拆包方法:
另外,请不要以内置对象(dict、list、tuple等)命名变量。你知道吗
如果您使用的是Python 3,则可以使用所谓的f字符串:
输出:
如果您想了解更多关于f字符串的信息,请参见tutorial。请记住,此解决方案仅适用于Python3.3及更新版本。你知道吗
相关问题 更多 >
编程相关推荐