在Python中使用range作为字典键,我有什么选项?

2024-04-28 18:07:10 发布

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

这是我的第一篇文章,我对编程很陌生,所以我可能无法恰当地表达我的问题,但我会尽力的!

tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}

ub_tries = user input

tries = 1

input ('\nCome on make your ' + tries_dict.get(tries) + guess: ')

这3个元素是我创建的数字猜谜游戏的一部分,我将它们包含在一个while循环中,在每个错误的答案后tries += 1

如您所见,在我的字典中,前4个答案和游戏结束前最后一个可能的机会都有自定义值,下面是我试图做的:

我想找到一种方法,在“第四个”和“最后一个”之间为每个答案/键设置“下一个”值。

如所示:

tries = 5

Come on make your next guess

tries = 6

Come on make your next guess

等等

我确实找到了一种复杂循环的方法,但作为一种好奇的类型,我想知道更有效/实用的方法来实现这一点。

以下是一些我想了想却没能上班的选择:

  1. 使用范围作为键
  2. 找到生成值介于4和ub_tries之间的列表的方法,并将该列表用作键

因此,一般来说:如何创建一种方法来获得字典中未指定的键的一般答案(next或其他)?

任何反馈都将非常感谢,请随时要求澄清,因为我可以告诉自己我的问题是有点混乱。

我希望我在编程和提出相关问题时变得更加狡猾,到目前为止,我的编程几乎和我的总结技能一样混乱,唉!


Tags: 方法答案游戏inputyourmake字典on
3条回答

我不确定这是否是你想要的,但^{}可能是答案:

>>> ub_tries = 20
>>> tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}
>>> tries_dict.get(1, 'next')
'first'
>>> tries_dict.get(4, 'next')
'fourth'
>>> tries_dict.get(5, 'next')
'next'
>>> tries_dict.get(20, 'next')
'last'
>>> tries_dict.get(21, 'next')
'next'

当然,您可以用不同的方式将其包装成一个函数。例如:

def name_try(try_number, ub_tries):
    tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}
    return tries_dict.get(try_number, 'next')

无论如何,dict.get(key, default=None)dict[key]类似,只是如果key不是成员,则返回default,而不是引发KeyError

至于你的建议:

using a range as a key??

当然,您可以这样做(如果您使用的是Python 2而不是3,那么请使用xrange作为range),但是它会有什么帮助呢?

d = { range(1, 5): '???', 
      range(5, ub_tries): 'next', 
      range(ub_tries, ub_tries + 1): 'last' }

这是完全合法的,但是d[6]会引发一个KeyError,因为6range(5, ub_tries)不是一回事。

如果希望这样做,可以构建一个RangeDictionary,如下所示:

class RangeDictionary(dict):
    def __getitem__(self, key):
        for r in self.keys():
            if key in r:
                return super().__getitem__(r)
        return super().__getitem__(key)

但这远远超出了“初学者的Python”的范围,即使对于这种效率极低、不完整且不健壮的实现,我也不建议这么做。

finding a way to generate a list with values between 4 and ub_tries and using such list as a key

你是说这样?

>>> ub_tries = 8
>>> tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}
>>> tries_dict.update({i: 'next' for i in range(5, ub_tries)})
>>> tries_dict
{1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'next', 6: 'next', 7: 'next', 8: 'last'}
>>> tries_dict[6]
'next'

这很有效,但可能不是一个好的解决方案。

最后,您可以使用defaultdict,它允许您将默认值烘焙到字典中,而不是将其作为每个调用的一部分传递:

>>> from collections import defaultdict
>>> tries_dict = defaultdict(lambda: 'next', 
...                          {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'})
>>> tries_dict
defaultdict(<function <lambda> at 0x10272fef0>, {8: 'last', 1: 'first', 2: 'second', 3: 'third', 4: 'fourth'})
>>> tries_dict[5]
'next'
>>> tries_dict
defaultdict(<function <lambda> at 0x10272fef0>, {1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'next', 8: 'last'})

但是,请注意,这会在第一次请求时永久地创建每个元素,并且您必须创建一个返回默认值的函数。这使得它对于更新值的情况更加有用,并且只希望以默认值作为起点。

我明白你的意图了吗?

max_tries = 8

tries_verbage = {
    1: 'first',
    2: 'second',
    3: 'third',
    4: 'fourth',
    max_tries: 'last'
    }

for i in xrange(1, max_tries + 1):
    raw_input('Make your %s guess:' % tries_verbage.get(i, 'next'))

回报

Make your first guess:1
Make your second guess:2
Make your third guess:3
Make your fourth guess:4
Make your next guess:5
Make your next guess:6
Make your next guess:7
Make your last guess:8

你为什么不列个单子呢?

MAX_TRIES = 10
tries_list = ["first", "second", "third", "fourth"]

for word in (tries_list[:MAX_TRIES-1] + 
             (["next"] * (MAX_TRIES - len(tries_list) - 1)) + ["last"]):
    result = raw_input("Come on, make your {} guess:".format(word))

注意,这段代码不能按计划工作,但我认为这不会是个问题。

相关问题 更多 >