使输出在python中看起来很漂亮和干净

时间:2013-12-02 22:12:39

标签: python python-2.7 python-3.x

我是python的新手。我只是想知道,你如何使输出看起来干净整洁?因为我的搜索和排序函数输出看起来像这样

"[{u'id': 1,
  u'name': u'ProPerformance',
  u'price': u'$2000',
  u'type': u'Treadmill'},
 {u'id': 2, u'name': u'Eliptane', u'price': u'$1500', u'type': u'Elliptical'},
 {u'id': 5,
  u'name': u'SupremeChest',
  u'price': u'$4000',
  u'type': u'Chest Press'},
 {u'id': 12, u'name': u'PowerCage', u'price': u'$5000', u'type': u'Squat'}]

---Sorted by Type---
[{u'id': 5,
  u'name': u'SupremeChest',
  u'price': u'$4000',
  u'type': u'Chest Press'},
 {u'id': 2, u'name': u'Eliptane', u'price': u'$1500', u'type': u'Elliptical'},
 {u'id': 12, u'name': u'PowerCage', u'price': u'$5000', u'type': u'Squat'},
 {u'id': 1,
  u'name': u'ProPerformance',
  u'price': u'$2000',
  u'type': u'Treadmill'}]

我希望我的输出看起来像这样

"RunPro $2000 Treadmill
 Eliptane $1500 Elliptical
 SupremeChest $4000 Chest Press
 PowerCage $5000 Squat”

---Sorted by Type---
RunPro $2000 Chest Press
Eliptane $1500 Elliptical
SupremeChest $4000 Squat
PowerCage $5000 Treadmill”

有人可以帮帮我吗?我一直试图想出这个问题就像一个小时一样,这真的让我很紧张,任何帮助都会非常感激。 这是我的代码

def searchEquipment(self,search):
    foundList = []
    workoutObject =self.loadData(self.datafile)

    howmanyEquipment = len(workoutObject["equipment"])

    for counter in range(howmanyEquipment):
        name = workoutObject["equipment"][counter]["name"].lower()
        lowerCaseSearch = search.lower()
        didIfindIt =  name.find(lowerCaseSearch) 
        if didIfindIt >= 0:
            foundList.append(workoutObject["equipment"][counter])
    return foundList

def sortByType(self,foundEquipment):
    sortedTypeList = sorted(foundEquipment, key=itemgetter("type"))   
    return sortedTypeList

我尝试将foundList.append(workoutObject["equipment"][counter])替换为workoutObject["equipment"][counter]["name"],但这会影响我的排序功能。

感谢

1 个答案:

答案 0 :(得分:4)

简短的回答是研究string formatting operations in Python。如果你看那里你可以找出如何根据你的需要格式化不同的数据类型。

更长的答案,基本上会让我们为您编写代码,但作为初学者:

for equip in sortedTypeList:
    print '{0} {1} {2}'.format(equip['name'],equip['price'],equip['type'])
相关问题