Skip to content Skip to sidebar Skip to footer

How Do I Get Next Element From List After Search String Match In Python

Hi Friends I have a list where I'm searching for string and along with searched string I want to get next element of list item. Below is sample code >>> contents = ['apple

Solution 1:

What about:

def find_adjacents(value, items):
    i = items.index(value)
    return items[i:i+2]

You'll get a ValueError exception for free if the value is not in items :)

Solution 2:

I might think of itertools...

>>>import itertools>>>contents = ['apple','fruit','vegi','leafy']>>>icontents = iter(contents)>>>iterable = itertools.dropwhile(lambda x: 'fruit'notin x, icontents)>>>next(iterable)
'fruit'
>>>next(iterable)
'vegi'

Note that if you really know that you have an exact match (e.g. 'fruit' == data instead of 'fruit' in data), this becomes easier:

>>> ix = contents.index('fruit')
>>> contents[ix: ix+2]
['fruit', 'vegi']

In both of these cases, you'll need to specify what should happen if no matching element is found.

Solution 3:

One way to do that is to iterate over the list zipped with itself.

Calling zip(contents, contents[1:]), allows the data variable to take on these values during the loop:

('apple', 'fruit')
('fruit', 'vegi')
('vegi', 'leafy')

in that order. Thus, when "fruit" is matched, data has the value ('fruit', 'vegi').

Consider this program:

contents = ['apple','fruit','vegi','leafy']
info = [datafordatain zip(contents,contents[1:]) if'fruit' == data[0]]
print(info)

We compare "fruit" to data[0], which will match when data is ('fruit', 'vegi').

Solution 4:

This straightforward imperative approach worked for me:

contents = ['apple', 'fruit', 'vegi', 'leafy']
result='<no match or no successor>'
search_term ='fruit'for i inrange(len(contents)-1):
   if contents[i] == search_term:
       result= contents[i+1]
print result

Note that you don't specify what the behavior should be for 1) not finding the search term, or 2) finding a match at the end of the list.

Post a Comment for "How Do I Get Next Element From List After Search String Match In Python"