Python: match two elements in a tuple, return 3rd

I have a set of input conditions that I need to compare and produce a third value based on two inputs. a list of 3 tuple elements seems like a smart choice for this. Where I could use any help, we build a compact method for processing it. I set out the structure, which I thought to use as follows:

input1 (string) is compared with the first element, input2 (string) is compared with the second element, if they match, returns the third element

('1','a', string1) ('1','b', string2) ('1','c', string3) ('1','d', string3) ('2','a', invalid) ('2','b', invalid) ('2','c', string3) ('2','d', string3) 
+4
source share
3 answers

Create a dict, dicts can have a tuple as keys and store the third element as a value.

Using dict will provide O(1) lookup for any pair (input1,input2) .

 dic = {('1','a'): string1, ('1','b'):string2, ('1','c'): string3....} if (input1,input2) in dic: return dic[input1,input2] else: #do something else 

Using a list of tuples in this case will be the O(N) approach, since for each input1 , input2 you need to input2 over the entire list of tuples (in the worst case).

+6
source

You can use a dict with a key from 2 tuples, and its value as a string / any, and then you can keep only valid values โ€‹โ€‹in mind and have a default value if you want ... (using dict.get )

So, if you have a list of refs , you can convert them to a dict and search as such:

 refs = [ ('1','a', 'string1'), ('1','b', 'string2'), ('1','c', 'string3'), ('1','d', 'string3'), ('2','a', 'invalid'), ('2','b', 'invalid'), ('2','c', 'string3'), ('2','d', 'string3') ] lookup = {ref[:2]:ref[2] for ref in refs} print lookup['1', 'd'] #string3 print lookup.get(('I do not', 'exist'), 'uh oh, in trouble now!') # uh oh, in trouble now! 
+2
source
 def checkIfSame(t): if t[0] == t[1]: return t[2] 

I am sure this will work for you.

0
source

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


All Articles