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

0 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'}]
Run Code Online (Sandbox Code Playgroud)

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

"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”
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?我一直在尝试解决这个问题大约一个小时,这真的让我感到压力很大,任何帮助都将不胜感激。这是我的代码

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
Run Code Online (Sandbox Code Playgroud)

我试图替换foundList.append(workoutObject["equipment"][counter])为打印,workoutObject["equipment"][counter]["name"]但它弄乱了我的排序功能。

谢谢

小智 5

简短的回答是研究Python 中的字符串格式化操作。如果您查看那里,您可以弄清楚如何根据您的需要格式化不同的数据类型。

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

for equip in sortedTypeList:
    print '{0} {1} {2}'.format(equip['name'],equip['price'],equip['type'])
Run Code Online (Sandbox Code Playgroud)