[英]Python dict to user format string
轉換Python字典的最簡單方法是什么,例如:
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
您可以省略方括號以避免構建中間列表:
''.join('%s %s\n' % o for o in a.items())
由於您在詢問map
,因此這是使用map
編寫的一種方法:
''.join(map(lambda o:'%s %s\n' % o, a.items()))
這是一個優先選擇的問題,但是我個人覺得它比原始版本更難閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.