我有一个返回json格式数据集的函数。这是一个样本:
[{u'category': [u'Transfer', u'Withdrawal', u'ATM'], u'category_id': u'21012002', u'_account': u'XARE85EJqKsjxLp6XR8ocg8VakrkXpTXmRdOo', u'name': u'ATM Withdrawal', u'amount': 200, u'meta': {u'location': {u'city': u'San Francisco', u'state': u'CA'}}, u'date': u'2014-07-21', u'score': {u'location': {u'city': 1, u'state': 1}, u'name': 1}, u'_id': u'0AZ0De04KqsreDgVwM1RSRYjyd8yXxSDQ8Zxn', u'type': {u'primary': u'special'}, u'pending': False}]
for trans in foodie_data:
print 'Name={},Amount={},Date={}, Categories ={}\n'.format(trans['name'],trans['amount'],trans['date'],trans['category'])
此脚本打印:
Name=ATM Withdrawal,Amount=200,Date=2014-07-21,Categories=[u'Transfer', u'Withdrawal', u'ATM']
我希望它将Categories作为字符串而不是列表返回:
Name=ATM Withdrawal,Amount=200,Date=2014-07-21,Categories='Transfer, Withdrawal,ATM']
最有效的方法是什么?
答案 0 :(得分:2)
您可以加入类别元素:
>>> categories = [u'Transfer', u'Withdrawal', u'ATM']
>>> ",".join(categories)
u'Transfer,Withdrawal,ATM'
并在打印输出时使用它:
",".join(trans['category'])
答案 1 :(得分:2)
代码中的两个快速修复应该解决它
trans['category']
返回的列表,使其成为字符串而不是列表的字符串表示。引用category
的格式说明符,即Categories =\'{}\'
for trans in foodie_data:
print 'Name={},Amount={},Date={}, Categories =\'{}\'\n'.format(
trans['name'],
trans['amount'],
trans['date'],
', '.join(trans['category']))
答案 2 :(得分:0)
您也可以直接使用str.format
来获取其他值:
for trans in foodie_data:
print "Name={name},Amount={amount},Date={date}," \
"Categories='{}'\n".format(",".join(trans["category"]),**trans)
Name=ATM Withdrawal,Amount=200,Date=2014-07-21,Categories='Transfer,Withdrawal,ATM'