开发者

Python: Get items that follow a specified element of a list

开发者 https://www.devze.com 2023-02-02 10:40 出处:网络
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

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)?

So, inputing 'ONE' would return ['TWO', 'SEVEN'] and inputing 'SEVEN' would return ['TWELVE', None].

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(str开发者_运维问答ing_list):
        follows.append(string_list[index+1])
        string_list = string_list[index+1:]
    else:
        follows.append(None)
        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]


Maybe this?

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:

  1. Find the first index of the element.
  2. Get everything after that element.
  3. Make a set out of those elements, since you apparently don't want duplicates.

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:

  1. Get pairs of adjacent elements, letting the last element be paired with None.
  2. Return an iterable of the second element from each pair whose first element matches.

That looks like:

(x[1] for x in zip(the_list, the_list[1:] + [None]) if x[0] == the_element)
0

精彩评论

暂无评论...
验证码 换一张
取 消