在Python中使用范围作为字典键,我有什么选项? [英] use a range as a dictionary key in Python, what option do I have?

查看:147
本文介绍了在Python中使用范围作为字典键,我有什么选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章,我在编程方面很新,所以我可能无法适当地传达我的问题,但我会尽力而为!

  attempts_dict = {1:'first',2:'second',3:'third',4:'4th',ub_tries:'last'} 

ub_tries =用户输入

尝试= 1

输入('\\\
Come on make your'+ attempts_dict.get(attempts)+ guess:')

这3个元素是我创建的一个猜测游戏的一部分,我将它们包含在一个 while 循环,其中尝试+ = 1 每个错误的答案。



正如你所看到的,在我的字典中,前4个答案的自定义值和游戏结束前的最后一个机会,所以这里是我试图do:



我想找到一种方法,在第四和最后一个之间为每个答案/键提供NEXT值。



如下:

  attempts = 5 

来吧你的下一个猜测

尝试= 6

来吧,让你的下一个猜猜

等等



我确实找到了一种复杂的循环方式,但是我想知道更有效/实用的方式



以下是我想到的一些选项,但无法上班:


  1. 使用范围作为键

  2. 找到一种方法来生成值介于4和 ub_tries 之间的列表,使用该列表作为关键

所以一般来说:怎么可以一个创建一个方法来获得一个没有在字典中指定的键的一般答案(下一个或什么)?



任何反馈将不胜感激,要求澄清,因为我可以告诉自己我的问题是有点混乱。



我希望我在编程和提出相关问题上更加狡猾,到目前为止,我的编程几乎像我的总结技巧一样凌乱!

解决方案

我不知道这是否是你想要的,但是 dict.get 可能是答案:

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

当然可以以各种不同的方式将其包装在一个功能中。例如:

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

无论如何, dict.get(key,default = None)就像 dict [key] ,除了如果 key 不是成员,而不是提高 KeyError ,它返回默认



至于您的建议:


使用范围作为一个键?


当然可以这样做(如果您使用的是Python 2而不是3,则对范围使用 xrange ),但是如何帮助?

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

这是完全合法的,但是 d [6] i将提出一个 KeyError ,因为 6 range不同5,ub_tries)



如果你想要这样工作,你可以建立一个 RangeDictionary 像这样:

  class RangeDictionary(dict):
def __getitem __(self,key):
for self inkey():
如果键入r:
return super().__ getitem __(r)
return super().__ getitem __(key)

但是这远远超出了初学者Python,即使这个可怕的低效,不完整和非强大的实现,所以我不会建议它。


找到一种方法来生成一个列表,值为4和ub_tries之间,并使用这样的列表作为键


你的意思是这样的?

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

这有用,但它可能不是那么好



最后,您可以使用 defaultdict ,这样可以将默认值烘焙到字典中,而不是作为每个通话的一部分传递:

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

但是,请注意,这会在您首次请求时永久创建每个元素它 - 你必须创建一个返回默认值的函数。这使得它对于您要更新值的情况更为有用,只需要默认为起点。


This is my first post and I'm quite new at programming, so I might not be able to convey my question appropriately, but I'll do my best!

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: ')

These 3 elements are part of a number guess game I created, and I included them in a while loop where tries += 1 after each wrong answer.

As you can see, in my dictionary there are custom values for the first 4 answers and the last possible chance before the game is over, so here is what I tried to do:

I wanted to find a way to have the 'NEXT' value for every answer/key between 'fourth' and 'last'.

As in:

tries = 5

Come on make your next guess

tries = 6

Come on make your next guess

and so on

I did find a way with some complex looping, but being the curious type I wanted to know of more efficient/practical ways to accomplish this.

Here are some options i thought about but couldn't get to work:

  1. Using a range as a key
  2. Finding a way to generate a list with values between 4 and ub_tries and using that list as a key

So generally speaking: how can one create a way to have this general answer (next or whatever) for keys that aren't specified in a dictionary?

Any feedback would be greatly appreciated, feel free to ask for clarifications since I can tell myself my question is kind of messy.

I hope I get more crafty both at programming and asking related questions, so far my programming is nearly as messy as my summary skills, sigh!

解决方案

I'm not sure whether this is what you want, but dict.get may be the answer:

>>> 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'

Of course you could wrap this up in a function, in various different ways. For example:

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

At any rate, dict.get(key, default=None) is like dict[key], except that if key is not a member, instead of raising a KeyError, it returns default.

As for your suggestions:

using a range as a key??

Sure, you can do that (if you're in Python 2 instead of 3, use xrange for range), but how would it help?

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

That's perfectly legal—but d[6] is going to raise a KeyError, because 6 isn't the same thing as range(5, ub_tries).

If you want this to work, you could build a RangeDictionary like this:

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

But that's well beyond "beginners' Python", even for this horribly inefficient, incomplete, and non-robust implementation, so I wouldn't suggest it.

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

You mean like this?

>>> 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'

That works, but it's probably not as good a solution.

Finally, you could use defaultdict, which lets you bake the default value into the dictionary, instead of passing it as part of each call:

>>> 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'})

However, note that this permanently creates each element the first time you ask for it—and you have to create a function that returns the default value. This makes it more useful for cases where you're going to be updating values, and just want a default as a starting point.

这篇关于在Python中使用范围作为字典键,我有什么选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆