python - 如果键和值不唯一,则字典不会更新

标签 python python-3.x dictionary

我是Python新手,我正在创建这个赌博游戏,用户可以选择对将生成的符号进行下注(最终-还没有到达那里)。我创建一个字典来保存用户下注金额(值)以及与他们下注的符号相对应的数字(键)的数据。每个玩家都可以选择每轮下注 1 次以上。我遇到一个问题,如果两个不同的玩家输入相同的下注和符号组合(例如 1(皇冠)10 美元),那么字典将不会更新为包含 2 个单独的 1:10 条目,它只会有一个 1 条目: 10.这就是我现在正在处理的事情

def getPlayers():

    print("Hello and Welcome to the Crown and Anchor Game")
    num = int(input('Please enter the number of people playing today: ')) # takes the number of people who are playing from the user
    scoreInit = [] # creating an empty list for the players inital score of 10

    for i in range(num): # for loop to append the inital score of 10 to the empty list scoerInit for the amount of players input 
        scoreInit += i * [10]

    return scoreInit # returns the list of inital scores for the amount of players playing


def collectBets(balance):
    bets = {}
    index = 0
    for i in balance:
        index += 1
        print('Player %d, what would you like to do this round?'  % (index))
        print('1: Bet on a symbol')
        print('2: Skip this round')
        userOpt = int(input('Please enter 1 or 2 depending on your choice: ')) # assigning what the user inputs as the variable 'usesrOpt'
        if userOpt == 1: # if user decides to bet:
            betTimes = int(input('How many times would you like to bet this round?: '))
            for a in range(betTimes):
                betAmount = int(input('Enter the amount you would like to bet this round: $1, $2, $5, or $10: '))
                symbol = int(input('Enter the number corresponding to the symbol you would like to bet on\n' # asking user what symbol they want to bet on - assigning it to a variable
                                       '1: Crown\n'
                                       '2: Anchor\n'
                                       '3: Heart\n'
                                       '4: Diamond\n'
                                       '5: Club\n'
                                       '6: Spade\n'
                                       ))                       

            bets.update({symbol:betAmount})


print(bets)

def main():
    balance1 = getPlayers()
    collectBets(balance1)

main()

任何帮助将不胜感激!谢谢!

最佳答案

最好将 Python 字典视为“一组无序的键:值对,要求键是唯一的(在一个字典内)”。 https://docs.python.org/3/tutorial/datastructures.html

话虽如此,每当用户 A 选择 10,然后用户 B 选择 10;用户 A 的选择实际上被用户 B 的选择覆盖。单个字典只能保存 10 次作为键。为了解决您的解决方案,您将不得不使用一些其他数据结构。字典中的键应该是唯一的。

解决您的问题的方法可能是使用不同级别的词典。您可以拥有一个玩家姓名字典,其中包含其值及其符号的字典。但是,您的玩家名称必须是唯一的,否则您会遇到同样的问题。

关于python - 如果键和值不唯一,则字典不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543384/

相关文章:

python - 如何从 qcombobox 获取 itemdata?

python - 从表中仅抓取具有今天日期的行

Python:如何判断列表中的元素是否包含某个数字?

python - 有条件分箱

python-3.x - python : Maximum difference between elements in a list

python - line.strip() 方法说明

dictionary - 如何在 Solr 的 POJO 中存储 map ?

python的**kwargs效率

python - 连续减法 - Python 3.X

python - 查找字典中所有唯一的键对