2012-03-21 58 views
0

在Python中是否有像「無限字典」的東西?Python中是否有「無限字典」?

更準確地說,是有什麼地方 - 我可以把價值觀就像一本字典, - 但也許還告訴我如何映射一鍵的值, 功能 - 一個映射,或許也未嘗一個(有限的)一組鍵的關鍵,然後給出相應的值? 以另一種方式表達,我想要的是下面的「東西」: 我以某種方式初始化它(給出值,函數,不管),然後它只是爲每個鍵提供一個值(根據請求)。

+0

所以,如果我理解正確的這個,你想給字典中鍵,把它給你,你沒有插入到字典中的價值? (你希望它從一個鍵生成一個值?) – Corbin 2012-03-21 20:35:22

+0

你如何想象這種混合的特定值和自動生成的值工作?它是如何決定是使用特定的值還是調用哪個函數來產生一個值? – 2012-03-21 20:35:28

+0

我有點困惑,你到底想要什麼......爲什麼不用簡單的字典呢?你有沒有對python字典做過任何研究? – 2012-03-21 20:35:34

回答

3

您將需要使用特殊方法__getitem__(self,key)創建一個類,該類將爲該密鑰返回適當的值。

4

你需要什麼叫做「功能」。

現在,在一個不太諷刺注:我不知道究竟你想達到什麼樣的,但這裏有一個例子:

你想要的一段代碼,返回第n個元素在算術級數。你可以用函數這樣來做:

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 

這可如果,例如,你需要保留狀態的功能進行擴展。

希望這有助於

1

一個簡單的方法來做到這一點是使用函數對象兩個用例。如果你想使用鍵值函數,你可以直接使用它作爲參考。爲了使普通字典適應該界面,可以將其包裝在lambda block中。像這樣:

# Use function as dictionary 
def dict_func(key): 
    return key * key 
dictionary = dict_func 
print dictionary(2) # prints 4 

# Use normal dictionary with the same interface 
normal_dict = {1: 1, 2: 4, 3: 9} 
dictionary = lambda(key): normal_dict[key] 
print dictionary(2) # also prints 4 

# Lambda functions store references to the variables they use, 
# so this works too: 
def fn_dict(normal_dict): 
    return lambda(key): normal_dict[key] 
dictionary = fn_dict({1: 1, 2: 4, 3: 9}) 
print dictionary(3) # prints 9 
1

我想你想是這樣的,在那裏你dict行爲像一個正常的字典,而是特殊的鍵,你想改變的行爲例如

class InfiniteDict(dict): 
    def __init__(self, *args, **kwargs): 
     self.key_funcs = kwargs.pop('key_funcs', []) 
     super(InfiniteDict, self).__init__(*args, **kwargs) 

    def __getitem__(self, key): 
     try: 
      return super(InfiniteDict, self).__getitem__(key) 
     except KeyError: 
      return self._get_value_from_functions(key) 

    def _get_value_from_functions(self, key): 
     """ 
     go thru list of user defined functions and return first match 
     """ 
     for key_func in self.key_funcs: 
      try: 
       return key_func(key) 
      except KeyError: 
       pass 

     raise KeyError(key) 

def double_even_int(key): 
    try: 
     if int(key)%2 == 0: 
      return int(key)*2 
     else: 
      raise KeyError(key) 
    except ValueError: 
     raise KeyError(key) 

def tripple_odd_int(key): 
    try: 
     if int(key)%2 == 1: 
      return int(key)*3 
     else: 
      raise KeyError(key) 
    except ValueError: 
     raise KeyError(key) 

inf = InfiniteDict(key_funcs=[double_even_int, tripple_odd_int]) 
inf['a'] = 'A' 

print inf['a'], inf[1], inf['2'] 

輸出:

A 3 4 
2

如果您想爲現有的鍵不存在的鍵正常行爲,和特殊的行爲,還有的__missing__方法就是所謂的丟失的鑰匙。

class funny_dict(dict): 
    def __missing__(self, key): 
     return "funny" * key 

d = funny_dict() 
d[1] = "asdf" 
d[3] = 3.14 
for i in range(5): 
    print(i, d[i]) 

print(d) 

輸出:

0 
1 asdf 
2 funnyfunny 
3 3.14 
4 funnyfunnyfunnyfunny 
{1: 'asdf', 3: 3.14}