The most efficient way to find the next element in a tuple

I have a system in which I often (but not constantly) have to find the next element in a tuple. I am currently doing it like this:

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) 

All elements are unique, and I don’t get stuck in the tuple, I can do something even earlier in the program, if necessary.

Since I need to do this a lot , I was wondering if there is a more efficient way to do this?

+6
source share
2 answers

Use dict here, dicts provides an O(1) list.index compared to list.index , which is an O(N) operation.

And this will work for strings too.

 >>> 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' 

Effective version with memory to create the above dict:

 >>> 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} 
+7
source

You might want to create an index using a dictionary:

 # The list >>> lis = (2,6,4,8,7,9,14,3) # build the index >>> index = dict(zip(lis, range(len(lis)))) >>> index {2: 0, 3: 7, 4: 2, 6: 1, 7: 4, 8: 3, 9: 5, 14: 6} # Retrieve position by using the index >>> index[6] 1 >>> lis[index[6]+1] 4 

If your list changes over time, you will have to rebuild the index. For a more efficient memory solution, you can use izip instead of `zip, as suggested in another answer.

+1
source

Source: https://habr.com/ru/post/947536/


All Articles