我的主要节目是Q& A游戏,最后我想将播放器的名称和得分写入文件,然后从文件中向用户显示最高分
文件编写部分如下所示
<!--- Your query
<cfquery name="messages" datasource="showcase_Uk">
select * from t_items where pid = 2 and spid = 45 ORDER BY uploadDate DESC
</cfquery>
--->
<!--- Building a new Query --->
<cfset messages = QueryNew("id,uploadDate,name,description")>
<cfset QueryAddRow(messages, 1)>
<cfset QuerySetCell(messages, "id", "123", 1)>
<cfset QuerySetCell(messages, "description", "a string", 1)>
<cfset QuerySetCell(messages, "name", "another string", 1)>
<cfset QuerySetCell(messages, "uploadDate", Now(), 1)>
<!--- From here on it is your code again --->
<cfset myStruct = StructNew() />
<cfset mystruct.link = "http://showcase.com" />
<cfset myStruct.title = "Examples" />
<cfset mystruct.description = "Examples from UK Showcase" />
<cfset mystruct.pubDate = Now() />
<cfset mystruct.version = "rss_2.0" />
<cfset myStruct.item = ArrayNew(1) />
<cfloop query="messages">
<cfset myStruct.item[currentRow] = StructNew() />
<cfset myStruct.item[currentRow].guid = structNew() />
<cfset myStruct.item[currentRow].guid.isPermaLink="YES" />
<cfset myStruct.item[currentRow].guid.value = '#messages.id#' />
<cfset myStruct.item[currentRow].pubDate = createDate(year(#messages.uploadDate#), month(#messages.uploadDate#), day(#messages.uploadDate#)) />
<cfset myStruct.item[currentRow].title = xmlFormat(#messages.name#) />
<cfset myStruct.item[currentRow].description = StructNew() />
<cfset myStruct.item[currentRow].description.value = xmlFormat(#messages.description#)>
</cfloop>
<cffeed action="create" name="#myStruct#" overwrite="true" xmlVar="myXML">
<!--- Show the complete xml --->
<cfoutput>#myXML#</cfoutput>
<br><br>
<cfoutput>#XMLFormat(myXML)#</cfoutput>
现在我获得了该文件的最高分数,但我怎样才能将其与#34; John&#34;为了显示得分和名字?
答案 0 :(得分:3)
请勿使用eval()
。
而不是:
scoresList = []
for i in content:
name, score = i.split(" ")
scoresList.append(eval(score))
执行以下操作:
content = {name:int(score) for name, score in (item.split() for item in content)}
这将创建以下形式的字典:
{'Mary': 200, 'Alex': 300, 'John': 500}
您现在可以按排序方式显示它:
for item in sorted(content, key=content.get):
print(item, content.get(item))
这将打印从最低到最高的名称和分数:
Mary 200
Alex 300
John 500
如果您希望按降序列出,请为排序功能指定sorted(content, key=content.get, reverse=True)
。
答案 1 :(得分:2)
最简单的方法是使用列表。包含元组的列表使用元组中的第一个元素自动排序。因此,将您的最后几行更改为:
scoresList = []
for i in content:
name, score = i.split(" ")
scoresList.append(float(score), name))
scoresList.sort()
maxscore = scoresList[0]
注意:我不记得它将对其进行排序的顺序,您可能需要将reverse=True
添加到sort()
参数