python字典增加元素,在python中添加元素到字典?

I'm relatively new here, so please tell me if there is anything I should know or any mistakes I am making manner wise!

I am trying to add things onto a dictionary through random choice, but my code doesn't seem to work!

The file:

sports.txt

Soccer, Joshua

Lacrosse, Naome Lee

Soccer, Kat Valentine

Basketball, Huong

Tennis, Sunny

Basketball, Freddie Lacer

my code so far:

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()

I am trying to allow a user to input their name and preferred group of sport, and whatever sport they prefer will have a higher chance of being randomly picked then the others (for example if Jason chooses soccer his chances of getting in soccer may double).

I don't expect anyone to write code for me, I know it's time consuming and you have better things to do! But can anyone maybe explain to me how I would go about doing this? I understand how to make random choices but I don't know how I would "double" the chances.

Also I keep getting this error when running my code: NameError: global name 'random' is not defined

I thought I was doing that part right but now i'm stuck. Can anyone give their two cents on this?

解决方案

Try this:

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)

This will increase chances of preferred sport to be picked by 2.

And don't forget to import random

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值