我在这里比较新,所以请告诉我是否有任何我应该知道的事情或任何错误我都是明智的做法!
我试图通过随机选择将字符添加到字典中,但我的代码似乎不起作用!
文件:
sports.txt
Soccer, Joshua
Lacrosse, Naome Lee
Soccer, Kat Valentine
Basketball, Huong
Tennis, Sunny
Basketball, Freddie Lacer
我的代码到目前为止:
def sportFileOpen():
sportFile = open("sport.txt")
readfile = sportFile.readlines()
sportFile.close()
return(readfile)
def sportCreateDict(sportFile):
sportDict = {}
for lines in sportFile:
(sport, name) = lines.split(",")
if sport in sportDict:
sportDict[sport].append(name.strip())
else:
sportDict[sport] = [name.strip()]
return(sportDict)
def sportRandomPick(name, sport, sportDict):
if sport in sportDict:
ransport = random.choice(sportDict.keys())
sportDict[ransport].append(name)
print(name, "has been sorted into", ransport)
def main():
sportFile = sportFileOpen()
sportDict = sportCreateDict(sportFile)
name = input("Enter the name: ")
preferredSport = input("Which sport do they want? ")
sportRandomPick(name, preferredSport, sportDict)
main()
我试图允许用户输入他们的名字和喜欢的运动组,并且他们喜欢的任何运动将有更高的机会被随机选择然后其他人(例如,如果杰森选择足球,他获得足球的机会可能加倍) .
我不希望有人为我编写代码,我知道这很费时间,你有更好的事情要做!但任何人都可以向我解释我将如何做到这一点?我理解如何做出随机选择,但我不知道如何“加倍”机会.
此外,我在运行代码时不断收到此错误:NameError:未定义全局名称“random”
我以为我正在做那个部分,但现在我被卡住了.有人可以给他们两分钱吗?