Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [‘1G’, ’12F’, ‘231G’]
Output : [(0, 1), (1, 2), (2, 3)]
Input : test_list = [‘G’, ‘F’, ‘G’]
Output : [(0, 0), (1, 0), (2, 0)]
Method #1 : Using
enumerate() + list comprehension + isalpha()
The combination of above functions can be used to solve this problem. In this, we perform the task of working with indices using enumerate and characters filtering is done using isalpha().
The original list is : ['23f45.;4d', '5678d56d', '789', '5678g'] Character indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]
Method #2 : Using
regex() + loop
The combination of above functions can be used to solve this problem. In this, we perform task of filtering alphabets using regex expressions. Just returns the first occurrence of character in each string.
The original list is : ['23f45.;4d', '5678d56d', '789', '5678g'] Character indices : [(0, 2), (1, 4), (3, 4)]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course