从python Dict中删除项

2024-05-14 23:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,我觉得制作一个游戏“交易或不交易”的克隆版会很有趣。我在从我的案件目录中删除一个案件时遇到了问题。它失败了,出现了一个键错误。我试着在输入端把我的键变成一个字符串,但也失败了

import random

# List of deal or no deal case amounts
amounts = [0.1, 1, 5, 10, 25, 50, 75, 100, 200,
           300, 400, 500, 750, 1000, 5000, 10000,
           25000, 50000, 750000, 100000, 200000,
           300000, 400000, 500000, 750000, 1000000]

# Randomize the amounts for the cases
random.shuffle(amounts)

# Check our amounts now..
print('current amount order:', amounts)

# Create cases dict with amounts in random order
cases = dict(enumerate(amounts))

# Check the new dict.
print('current cases:', cases)

# Have the player select their case
yourCase = input(str('Select your case: '))

# Remove the case the user selected from the cases dict
try:
    del cases[yourCase]
except KeyError:
    print('Key not found!')

# Our cases dict now...
print('Now cases are:', cases)

Tags: thecheckorder交易randomcurrentnowdict
2条回答

您的键将是来自enumerateint,因此请首先将输入转换为int

# Have the player select their case
yourCase = input('Select your case: ')

# Remove the case the user selected from the cases dict
try:
    del cases[int(yourCase)]
except KeyError:
    print('Key not found!')
except ValueError:
    print('Invalid input!')

如果希望dict首先具有字符串键,可以执行以下操作:

# Create cases dict with amounts in random order
cases = {str(i): x for i, x in enumerate(amounts)}

您的键是数值的,并且是str中的默认输入,因此您需要将其转换为int

按以下方式更改输入行:

yourCase = int(input('Select your case: '))

相关问题 更多 >

    热门问题