Hem*_*lla 14 python performance dictionary
给定一个python字典和一个整数n,我需要访问nth键.我需要在我的项目中反复多次这样做.
我写了一个函数来做到这一点:
def ix(self,dict,n):
count=0
for i in sorted(dict.keys()):
if n==count:
return i
else:
count+=1
Run Code Online (Sandbox Code Playgroud)
但问题是如果字典很大,反复使用时间复杂性会增加.
有没有一种有效的方法来做到这一点?
我想你想做这样的事情,但是因为字典没有任何顺序所以键的顺序dic.keys可以是任何东西:
def ix(self, dic, n): #don't use dict as a variable name
try:
return list(dic)[n] # or sorted(dic)[n] if you want the keys to be sorted
except IndexError:
print 'not enough keys'
Run Code Online (Sandbox Code Playgroud)
dict.keys() 返回一个列表,所以你需要做的就是 dict.keys()[n]
但是,字典是一个无序集合,所以第n个元素在这个上下文中没有任何意义
对于那些想要避免创建新的临时列表只是为了访问第 n 个元素的人,我建议使用迭代器。
from itertools import islice
def nth_key(dct, n):
it = iter(dct)
# Consume n elements.
next(islice(it, n, n), None)
# Return the value at the current position.
# This raises StopIteration if n is beyond the limits.
# Use next(it, None) to suppress that exception.
return next(it)
Run Code Online (Sandbox Code Playgroud)
与首先将键转换为临时列表然后访问其第 n 个元素相比,这对于非常大的字典来说可以明显更快。