user2399453
user2399453

Reputation: 3081

Matching a pattern in a list of strings and returning a list of indexes

I want to do the following in python:

Input list: ['abc', 'def', 'abx', 'cfd', 'nab', 'fdd', 'aadsd_ab']
Input pattern: 'ab'
Output: Return [0,2,4,6], i.e a list of indexes for every entry in input list that contains input pattern. 

In this case 'abc', 'abx', 'nab', 'aadsd_ab' contain the pattern 'ab' so return the respective indexes [0, 2, 4, 6] What is the simplest way to do this in python?

Upvotes: 0

Views: 50

Answers (3)

Learner
Learner

Reputation: 5292

If want to use regex just for more control over the search

>>>l = ['abc', 'def', 'abx', 'cfd', 'nab', 'fdd', 'aadsd_ab']
>>>lst = []
>>>for i in l:
    if re.search(".*ab.*", i, re.IGNORECASE):
        lst.append(l.index(i))
>>>lst
>>>[0, 2, 4, 6]

Explanation: for every element in list l find if it matches the pattern .*ab.* if matches then get the index of that element and append it to the second list i.e. lst. regex pattern means find all ab that have any character before and after.

Upvotes: 0

Damian Chrzanowski
Damian Chrzanowski

Reputation: 479

You could also use enumerate, but a list comprehension is also great.

l = ['abc', 'def', 'abx', 'cfd', 'nab', 'fdd', 'aadsd_ab']
l_idx = []
for idx, value in enumerate(l):
    if 'ab' in value:
        l_idx.append(idx)
print l_idx

l_idx contains the values you were looking for. Good Luck !

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

You could use a list comprehension like so:

>>> words = ['abc', 'def', 'abx', 'cfd', 'nab', 'fdd', 'aadsd_ab']
>>> [idx for idx, word in enumerate(words) if 'ab' in word]
[0, 2, 4, 6]

Upvotes: 2

Related Questions