0

I have a list like this:

 lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]

I want to build a string indexer and convert it into:

 lst_converted = [[1,2,3], [4,1]]

Do some processing on the converted list and then if the output is [[3], [2]]

 lst_output = [['cd'], ['ab']]

Here,

  'ab' = 1
  'bc' = 2
  'cd' = 3
  'dg' = 4

Strings can be arbitrary and not necessarily characters. How to do this?

2
  • Strings can be arbitrary and not necessarily characters ... then you should give a more general example. Commented May 29, 2021 at 11:21
  • modified the example. Commented May 29, 2021 at 11:24

1 Answer 1

1

Use a list comprehension along with a dictionary to map the string literals to integer values:

d = {}
d['ab'] = 1
d['bc'] = 2
d['cd'] = 3
d['dg'] = 4

lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]
lst_converted = [[d[y] for y in x] for x in lst]
print(lst_converted)  # [[1, 2, 3], [4, 1]]
Sign up to request clarification or add additional context in comments.

Comments

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.