I have a list of strings similar to
['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN']. Given a string that I know is in the list, is there a simple way to return an iterable of all of the elements that follow that string (and
None if nothing follows it)?
'ONE' would return
['TWO', 'SEVEN'] and inputing
'SEVEN' would return
My current approach is to do something like:
follows = 
while test_string in string_list:
index = string_list.index(test_string)
if index + 1 < len(string_list):
string_list = string_list[index+1:]
string_list = 
But this seems overly cumbersome. If this is the best way, I can accept it. If there is a cleaner way, I'd love to learn it.
How about something like:
>>> a = ['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN'] >>> [a[x+1] if x+1 < len(a) else None for x in range(len(a)) if a[x] == 'ONE'] ['TWO', 'SEVEN']
l = ['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN'] k = 'ONE' [l[i+1] if i<len(l)-1 else None for i,e in enumerate(l) if e==k]
from itertools import izip [b for a, b in izip(string_list, string_list[1:] + [None]) if a == test_string]
Well... Feels like a generator could be a nice thing here.
>>> def follows(list, match): ... i = iter(list) ... x = next(i) ... while x: ... if x == match: ... try: ... yield next(i) ... except StopIteration: ... yield None ... x = next(i) ... >>> [x for x in follows(['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN'], 'SEVEN')] ['TWELVE', None] >>> [x for x in follows(['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN'], 'ONE')] ['TWO', 'SEVEN']
But cleaner? Matter of taste I guess.
The process is:
This looks like:
set(the_list[the_list.index(the_element) + 1:])
Now that I've figured out what you're actually asking:
The process is:
That looks like:
(x for x in zip(the_list, the_list[1:] + [None]) if x == the_element)