python - 如何知道列表中的元素是否在另一个列表中
问题描述
我目前正在开发这款游戏,与 Road Fighter 非常相似,问题是我需要保存玩家的分数,我正在使用 .txt 文件执行此操作,然后我必须显示最高分数。我正在尝试使用下面的代码执行此操作,我的问题是我需要将这些分数与玩家姓名匹配,而且我不明白我做错了什么顺便说一句,我应该这样做递归地
例如,函数 GetSortedScores 返回如下列表:
[10000, 3424, 788, 225, 177, 125, 95, 90, 80, 50, 3]
所以我想要做的是询问原始列表上面列表的元素是否与分数匹配,如果分数匹配,它应该创建一个包含玩家姓名和相应分数的列表,我正在寻找的结果因为是这样的:
[maicolvn 10000, playerone 3424, mike 788, jake 225, francis05 177, julia 125, playerTwo 95, player3 90, jerome 80, frank 50, luke 3]
当我尝试运行代码来测试它时,python 向我显示了这个错误
if sortedList == []:
RecursionError:比较超过最大递归深度
这也是我的 txt 文件的样子:
maicolvn,10000
mike,788
playerTwo,95
jake,225
francis05,177
luke,3
jerome,80
frank,50
player3,90
julia,125
playerone,3424
在此先感谢您的帮助,我才刚刚开始,所以感谢您的反馈
def TopScores():
list = GetSortedScores()
return TopAux(ReadFile(),list,[])
def TopAux(originalList,sortedList,newList):
if sortedList == []:
return newList
elif sortedList[0] == int(originalList[0].split(",")[1]):
return TopAux(originalList,sortedList[1:],[originalList[0].split(",")[0]+originalList[0].split(",")[1]]+newList) """This is supposed to get the the name and score of the player"""
else:
return TopAux(originalList,sortedList,newList)
def GetSortedScores():
return(SortScores(GetBestScores(ReadFile(),[])))
def GetBestScores(list,newList):
"""Get scores from file"""
if list == []:
return newList
elif isinstance(int(list[0].split(",")[1]),int):
return GetBestScores(list[1:],newList+[int((list[0].split(",")[1]))])
else:
return GetBestScores(list[1:],newList)
def SortScores(list):
"""Returns a list of scores in descending order"""
list.sort(reverse=True)
return list
def ReadFile():
"""This function reads the file of the scores
and return the content in a list"""
path = "TopScores.txt"
file = open(path)
content = file.readlines()
file.close()
return content
解决方案
您可以从文件中读取这样的分数:
path = "TopScores.txt"
scores = list()
with open(path) as f:
for l in f:
l = l.strip().split(',')
l[1] = int(l[1])
scores.append(l)
print(scores)
print(sorted(scores, key = lambda x: -x[1]))
使用 lambda 函数,您可以访问这些点并对它们进行排序而不是名称。之后它将跳过将点与名称匹配的步骤。
阅读您上面的脚本,我在第 9 行遇到语法错误。直到您的 RecursionError 才出现。也许你可以重组和清理你的代码?
另外:如果您经常在游戏期间为多个玩家更改分数,您可以在游戏运行期间将 player : score
配对存储在字典scores = dict()
中。通过这种方式,您可以简单地访问和更新分数:scores.get(<name>)
或通过设置它们scores[<name>] = score
。
如果您希望它们作为高分的排序列表:
sorted([[k,v] for k,v in scores.items()], reverse = True)
推荐阅读
- oracle - 如何创建具有唯一名称的表,然后将另一个表中的数据插入到该表中,最好使用单个触发器
- canvas - 列表视图中带有刻度/平移的画布。如何禁用滚动
- node.js - Nodejs区分http请求;具有相同公共 IP 的多个设备
- python - 使用 .NET WebAPI 最佳实践进行进程间通信
- javascript - 如何在javascript中修复每日更新程序
- java - JTable 记录不显示
- google-apps-script - Google 应用程序独立脚本 - 文件选择器身份验证失败
- javascript - JS:除非单击,否则防止文本输入字段获得焦点
- html - 如何使字体真棒图标按钮的禁用状态?
- android-studio - Android Studio 菜单中未显示“调试或配置文件 APK”选项