当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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(string_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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: