查找元组中下一个元素的最有效方法

kra*_*r65 6 python tuples next

我有一个系统,我经常(但不是经常)必须找到元组中的下一个项目.我现在这样做:

mytuple = (2,6,4,8,7,9,14,3)
currentelement = 4
def f(mytuple, currentelement):
    return mytuple[mytuple.index(currentelement) + 1]
nextelement = f(mytuple, currentelement)
Run Code Online (Sandbox Code Playgroud)

所有元素都是独一无二的,我不会被元组困住,如果需要,我可以在程序的早期做出其他的东西.

既然我需要做很多事情,我想知道是否有更有效的方法来做到这一点?

Ash*_*ary 7

在这里使用dict,dicts提供O(1)查找,比较list.index哪个是O(N)操作.

这也适用于字符串.

>>> lis = (2,6,4,8,7,9,14,3)
>>> dic = dict(zip(lis, lis[1:]))
>>> dic[4]
8
>>> dic[7]
9
>>> dic.get(100, 'not found') #dict.get can handle key errors
'not found'
Run Code Online (Sandbox Code Playgroud)

用于创建上述字典的内存高效版本:

>>> from itertools import izip
>>> lis = (2,6,4,8,7,9,14,3)
>>> it1 = iter(lis)
>>> it2 = iter(lis)
>>> next(it2)
2
>>> dict(izip(it1,it2))
{2: 6, 4: 8, 6: 4, 7: 9, 8: 7, 9: 14, 14: 3}
Run Code Online (Sandbox Code Playgroud)