gpt4 book ai didi

Python dict 到用户格式字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:36 24 4
gpt4 key购买 nike

转换 Python dict 的最简单方法是什么,例如:

a = {'a': 'value', 'b': 'another_value', ...}

使用用户格式转换成字符串,例如:

'%s - %s\n'

所以它给了我:

a - value
b - another_value

这行得通,但使用 map 可能会更短/更好(无需遍历集合)

''.join(['%s %s\n' % o for o in a.items()])

最佳答案

我会这样写:

>>> print '\n'.join(' '.join(o) for o in a.items())
a value
b another_value

或者:

>>> print '\n'.join(map(' '.join, a.items()))
a value
b another_value

关于Python dict 到用户格式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8894132/

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