Character Indices Mapping in String List – Python
We are given a string list we need to map characters to their indices. For example, a = [“hello”, “world”] so that output should be [[(‘h’, 0), (‘e’, 1), (‘l’, 2), (‘l’, 3), (‘o’, 4)], [(‘w’, 0), (‘o’, 1), (‘r’, 2), (‘l’, 3), (‘d’, 4)]].
Using a nested for
loop
A nested for loop iterates through each string in the list and then through each character within string. It maps each character to its corresponding index in the string creating a detailed character-index mapping.
a = ["hello", "world"]
ch = []
for string in a:
# Create a list of (char, index) pairs for each string
c = [(char, idx) for idx, char in enumerate(string)]
ch.append(c)
print(ch)
Output
[[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]]
Explanation:
- For each string in the list a list comprehension generates
(character, index)
pairs usingenumerate
. - Each list of pairs is appended to
ch
creating a list of character-index mappings for all strings which is then printed
Using dictionary comprehension
Dictionary comprehension can be used to map each character to its index in the string by iterating with enumerate
. This approach creates a dictionary for each string providing direct access to character indices.
a = ["hello", "world"]
# Create a list of dictionaries for each string
c = [{char: idx for idx, char in enumerate(string)} for string in a]
print(c)
Output
[{'h': 0, 'e': 1, 'l': 3, 'o': 4}, {'w': 0, 'o': 1, 'r': 2, 'l': 3, 'd': 4}]
Explanation:
- For each string a dictionary is created using {char: idx for idx, char in enumerate(string)}, mapping each character to its index.
- List comprehension stores these dictionaries in c resulting in a list of dictionaries representing character-index mappings for each string which is then printed.
Using defaultdict
from collections
defaultdict
from collections
can be used to group character indices in a list allowing multiple occurrences of the same character to be stored. It automatically initializes empty lists for new characters simplifying mapping process.
from collections import defaultdict
a = ["hello", "world"]
c = []
for string in a:
# Create a defaultdict to map characters to indices
m = defaultdict(list)
for idx, char in enumerate(string):
m[char].append(idx)
c.append(dict(m))
print(c)
Output
[{'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}, {'w': [0], 'o': [1], 'r': [2], 'l': [3], 'd': [4]}]
Explanation:
- For each string defaultdict(list) maps each character to a list of all its indices using m[char].append(idx) during iteration with enumerate.
- Each defaultdict is converted to a regular dictionary and appended to c resulting in a list of dictionaries mapping characters to their respective indices for each string.