Reputation: 141
I have a set of input conditions that I need to compare and produce a 3rd value based on the two inputs. a list of 3 element tuples seems like a reasonable choice for this. Where I could use some help is in building an compact method for processing it. I've laid out the structure I was thinking of using as follows:
input1 (string) compares to first element, input2 (string) compares to second element, if they match, return 3rd 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)
Upvotes: 4
Views: 1535
Reputation: 251096
Create a dict, dicts can have tuple as keys and store the third item as it's value.
Using a dict will provide an O(1)
lookup for any pair of (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 an O(N)
approach, as for every input1
,input2
you've to loop through the whole list of tuples(in worst case).
Upvotes: 7
Reputation: 95
def checkIfSame(t):
if t[0] == t[1]:
return t[2]
I'm pretty sure this should work for you.
Upvotes: 0
Reputation: 142206
Could use a dict with a 2-tuple as key, and its value as your string/whatever and then you can keep the look to only include valid values, and have a default value of invalid if you wished... (by using dict.get
)
So if you have a list of refs
, you can then convert them into a dict
and perform lookups 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!
Upvotes: 2