1

I need to iterate variable Y, compare each iteration with variable sublist Variable X and create a new string with results.

Y = 'ABCEF'

X =[('A', 1),('B', 4),('C', 6),('D', 7),('E', 8),('F', 9),('G', 10),('H', 11),('I', 12),('J', 13),('K', 14),('L', 15),('M', 16)]

The result is below after iterating Y.

Z = '14689'

Can someone shade some light on the resolution of this.

Y = 'ABCEF'

X =[('A', 1),('B', 4),('C', 6),('D', 7),('E', 8),('F', 9),('G', 10),('H', 11),('I', 12),('J', 13),('K', 14),('L', 15),('M', 16)]
j <= len(X) - 1 
result = ''

for i in Y:
    if i in X[0][j]:
        result.append(X[j])
else: 
    j = j -1
6
  • What language are you using? Commented Oct 21, 2019 at 1:02
  • I am using Python 3 Commented Oct 21, 2019 at 1:04
  • Is X stored as a string (a la JSON) or is that a literal Python list? Commented Oct 21, 2019 at 1:05
  • X is a list that contains within list of two digits each Commented Oct 21, 2019 at 1:06
  • So why is your question "iterate a string based on another string" when there's only 1 string? Commented Oct 21, 2019 at 1:07

2 Answers 2

2

You can creating a mapping dict from X so that you can iterate through Y to map each character to its value before joining them into a new string:

mapping = dict(X)
Z = ''.join(str(mapping[c]) for c in Y)

Z becomes: '14689'

Sign up to request clarification or add additional context in comments.

Comments

0
y = 'ABCEF'
x =  [('A', 1),('B', 4),('C', 6),('D', 7),('E', 8),('F', 9),('G', 10),('H', 11),('I', 12),('J', 13),('K', 14),('L', 15),('M', 16)]
result = ''
for i in y: 
    for j in range(len(x)): 
        if i in x[j]:
            result += str(x[j][1])
            break
print(result)

the output will be 14689

1 Comment

Thank you Habib. Your solution is perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.