简体   繁体   English

无法在python 2.7中迭代元组

[英]unable to iterate tuple in python 2.7

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. 我有以下要重复的第一个元组(例如,来自元组下方的0101AA),并用包含第二个和第三个(例如MTS,DL)的值替换输入字符串(如果它与输入字符串匹配)。

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. 我正在测试的代码将行作为完整的元组1(例如'0101AA,MTS,DL')给出行以及如何以有效方式检查输入字符串中元组1、2,e等的第一个col ...混淆了如何打破界限然后匹配它。

for counter,line in enumerate(mastertup):
    print line

In your case, mastertup is a list of string, convert it into a list of tuples by, 在您的情况下, mastertup是一个字符串列表,将其转换为元组列表,

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 . 如果我理解得很好,您想将映射从col1映射到col2,col2 Use dict to quickly look up, 使用dict快速查找,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM