Reputation: 89
I have following tuple which I want to iterate for the 1st value(say 0101AA from below tuple) & replace the inputstring with value comprising of 2nd & 3rd (say MTS, DL) in case it matches the input string.
mastertup = ('0101AA,MTS,DL', '03F0,MTS,DL', 'YG,MTS,GJ', 'YK,MTS,KO', 'YL,MTS,KL', '98765,MTS,RJ', '9234,MTS,TN', '919136,MTS,WB', 'YW,MTS,UPW', 'YX,MTS,KT')
inputstring='0101AA'
my code which I am testing gives line as complete tuple 1 (say '0101AA, MTS, DL') & how do I check in the input string in efficient manner for 1st col of tuple 1, 2, e etc... & really confused what to do for breaking the line & then matching it.
for counter,line in enumerate(mastertup):
print line
Upvotes: 1
Views: 79
Reputation: 18045
In your case, mastertup
is a list of string, convert it into a list of tuples by,
lists = [tuple(s.split(',')) for s in mastertup]
print(lists)
# Output
[('0101AA', 'MTS', 'DL'), ('03F0', 'MTS', 'DL'), ('YG', 'MTS', 'GJ'), ('YK', 'MTS', 'KO'), ('YL', 'MTS', 'KL'), ('98765', 'MTS', 'RJ'), ('9234', 'MTS', 'TN'), ('919136', 'MTS', 'WB'), ('YW', 'MTS', 'UPW'), ('YX', 'MTS', 'KT')]
If I understand well, you'd like to map from col1
to col2,col2
. Use dict
to quickly look up,
d = dict()
for s in mastertup:
str_list = s.split(',')
d[str_list[0]] = ','.join(str_list[1:])
# Test
inputstring = '0101AA'
inputstring = d.get(inputstring, inputstring) # if inputstring not in d, not mapping
print(inputstring)
# Output
MTS,DL
Upvotes: 2