Home > front end >  How to find specific element in a list with their relative position?
How to find specific element in a list with their relative position?

Time:03-14

My list contains several strings. I want to get the next element after the element, which equals to "PlayStation". How should I do that?

list_ = ['PlayStation', '9th Sep 1995 (USA)29th Sep 1995 (UK/EU)28th Apr 1995 (JPN)',  'PlayStation Network', '3rd May 2007 (USA), $5.9922nd Jun 2007 (UK/EU), £3.99', '']
[element.next() for element in list_ if element == 'PythonStation']

I tried to achieve that by using comprehension. But it returns as [].

CodePudding user response:

Assuming that I understood the question correctly and that there zero or one "PlayStation" string in your list.

list_ = ['PlayStation', '9th Sep 1995 (USA)29th Sep 1995 (UK/EU)28th Apr 1995 (JPN)',  'PlayStation Network', '3rd May 2007 (USA), $5.9922nd Jun 2007 (UK/EU), £3.99', '']
if "PlayStation" in list_:
    index = list_.index("PlayStation")
    if index < len(list) - 1 : # if "PlayStation" is found before at the last index
        print(index 1)
    else: # "PlayStation" is found at the last index no more element after this
        print(index)
else:
    print("No match found")

for one or more "PlayStation" string in list_

while "PlayStation" in list_:
    index = list_.index("PlayStation")
    if index < len(list) - 1 : # if "PlayStation" is found before at the last index
        print(index 1)
    else: # "PlayStation" is found at the last index no more element after this
        print(index)
    list_ = list_[index:] #update the list to check for "PlayStation" after index in `list_`

CodePudding user response:

Solution if "PlayStation" always occurs exactly once

Since you're looking for the position of an element, you should use index():

list_[list_.index("PlayStation") 1]

That will work if you know you'll find exactly one instance of "PlayStation" in list_ and it's never the last element.

Solution for multiple instances

If there might be several instances and you want the element after each instance, this comprehension will do that for you:

[y for x, y in zip(list_, list_[1:]) if x == "PlayStation"]

Here I'm using zip() to loop through pairs of each element and its successor, and printing the successor y if the element x is "PlayStation".

  • Related