Python非常生疏,我希望按如下方式排序和打印2D数组。使用studentName和studentScore填充2D字典。循环并向字典添加新项目。我添加了studentName和studentScore作为示例。我想按studentName排序和打印dataSet ......但不确定如何。任何帮助都一如既往地受到赞赏......
dataSet = {}
position = len(dataSet)
studentName = "Derek"
studentScore = "80%"
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})
我希望输出类似......
Student: Derek -- Score: 80%
当然,循环遍历dataSet中的每个项目
目前使用此...但是格式化为对象并且非常难看!
def viewScores(dataSet):
for x in dataSet:
for y in dataSet[x]:
print (y,':',dataSet[x][y])
答案 0 :(得分:1)
你应该检查python中词典的用法......你的问题可以这样解决:
def viewScores(dataSet):
for student in sorted(dataSet.keys()):
print ("{}: {}".format(student, dataSet[student]))
dataSet = {}
studentName = "Derek"
studentScore = "80%"
dataSet[studentName] = studentScore
dataSet["Zyline"] = "99%"
print(dataSet) # just to show it works (and it might be sorted in reverse order)
viewScores(dataSet)
此外,我建议将分数存储为数字而不是字符串,并仅在打印声明中添加百分号。
根据您的新要求(重复名称),我会这样解决:
def viewScores(dataSet):
for student in sorted(dataSet, key=lambda x: x["studentName"]):
print ("Student: {} -- Score {}%".format(student["studentName"], student["studentScore"]))
dataSet = []
studentID = 7
studentName = "Derek"
studentScore = 80
dataSet.append({"studentName": studentName, "studentScore": studentScore, "id": studentID})
dataSet.append({"studentName": "Zyline", "studentScore": 99, "id": 42})
print(dataSet) # just to show it works (and it might be sorted in reverse order)
viewScores(dataSet)
答案 1 :(得分:1)
这是另一种可能的解决方案,按名称排序然后得分。正如所建议的那样,将分数存储为整数更有意义,因为这样可以更容易排序。
def viewScores(dataSet):
entries = sorted([(dataSet[entry]['studentName'], dataSet[entry]['Score']) for entry in dataSet])
for name, score in entries:
print('Student: {} -- Score: {}%'.format(name, score))
dataSet = {}
position = len(dataSet)
studentName = "Derek"
studentScore = 80
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})
position = len(dataSet)
studentName = "Andrew"
studentScore = 90
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})
position = len(dataSet)
studentName = "Andrew"
studentScore = 9
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})
viewScores(dataSet)
对于此示例,它将显示以下输出:
Student: Andrew -- Score: 9%
Student: Andrew -- Score: 90%
Student: Derek -- Score: 80%
答案 2 :(得分:0)
首先,您应该使用.values()
获取字典的值。
然后,您可以轻松访问每个studentName
和studentScore
。我使用了list comprehension
最后,使用sorted()
对值进行排序。
valuesDict = dataSet.values()
valuesTuple = [(v["studentName"], v["Score"]) for v in valuesDict]
sortedValues = sorted(valuesTuple)
for student, score in sortedValues:
print "Student: %s -- Score: %s" % (student, score)