如果這是所有你要處理的值,結果,那麼dictionary是你所需要的
>>> Tuplelist = [(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)]
>>> my_map = dict(Tuplelist)
>>> my_map[1]
17
>>> my_map[5]
12
>>> my_map[23]
39
,如果你想它的功能是一種簡單
def my_fun(key):
return dict(Tuplelist)[key]
或類似
def my_fun(key):
Tuplelist = dict([(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)])
return Tuplelist[key]
或
MyValues = dict([(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)])
def my_fun(key):
return MyValues[key]
反正其他一些變化,如果這是你所需要的,我會使用詞典直接,而這使得做同樣更功能限制的方式。
你也可以做在列表的簡單線性搜索,但失去的速度字典報價
Tuplelist = [(1, 17), (2, 13), (3, 17), (4, 4), (5, 12), (6, 10), (7, 20), (18, 36), (22, 12), (23, 39)]
def my_func(key):
for k,v in Tuplelist:
if k == key:
return v
http://stackoverflow.com/help/mcve – Abhineet
目前還不清楚是什麼你」再問。難道你需要像字典這樣簡單的東西嗎? – Matthias
是的,這隻需要一本字典... –