我在这里相对较新,所以请告诉我是否有任何我应该知道的或我在礼貌上犯的任何错误!
我正在尝试通过随机选择将内容添加到字典中,但我的代码似乎不起作用!
文件: 运动.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: global name 'random' is not defined
我以为我做的那部分是对的,但现在我被卡住了。谁能为此付出两分钱?
最佳答案
试试这个:
def sportRandomPick(name, sport, sportDict):
if sport in sportDict:
ransport = random.choice(list(sportDict.keys()) + [sport]) # list of sports will contain preferred sport twice.
sportDict[ransport].append(name)
print(name, "has been sorted into", ransport)
这将增加 2 人选择首选运动的机会。
不要忘记import random
关于python - 在python中向字典添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40776193/