是否有“无限词典"?在Python中? [英] Is there an "infinite dictionary" in Python?

查看:90
本文介绍了是否有“无限词典"?在Python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有类似无限字典"的内容?

Is there something like an "infinite dictionary" in Python?

更确切地说,有什么地方 -我可以在字典中输入值, -但也许还有一个告诉我如何将键映射到值的函数, -也许还有一些将键映射到一组(有限)键,然后给出相应值的东西? 用另一种方式表述,我想拥有的是以下东西": 我以某种方式(给定值,函数等)初始化它,然后为每个键给我一个值(应要求提供).

More precisely, is there something where - i can put in values like in a dictionary, - but maybe also a function which tells me how to map a key to a value, - and maybe also something that maps a key to a (finite) set of keys and then gives the corresponding value? Formulated in another way, what I want to have is the following "thing": I initialize it in a way (give values, functions, whatever) and then it just gives me for each key a value (on request).

推荐答案

您需要的被称为函数".

What you need is called a "function".

现在,不那么讽刺了:我不知道您到底想达到什么目的,但这是一个例子:

Now, on a less sarcastic note: I don't know exactly what you are trying to achieve, but here's an example:

您需要一段代码,以算术级数返回第n个元素.您可以使用以下功能来做到这一点:

You want a piece of code that returns the nth element in an arithmetic progression. You can do it this way with functions:

def progression(first_element, ratio):
    def nth_element(n):
        return n*ratio + first_element
    return nth_element

my_progression = progression(2, 32)
print my_progression(17) # prints 546

例如,如果您需要一个保留状态的函数,可以对此进行扩展.

This can be extended if, for example, you need a function that retains state.

希望这会有所帮助

这篇关于是否有“无限词典"?在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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