Home > Software engineering >  Looping into a list to get the previous value of a particular value within that list
Looping into a list to get the previous value of a particular value within that list

Time:01-19

We have a list of strings here called list_strings `

list_strings =["john", "sarah", "bianca", "savie", "sandy", "john", "harry", "john", "debra", "john"]

If a specified value is "john" and can we get all the strings before john, so the output should look like this!`

result = ["none", "sandy", "harry", "debra]

CodePudding user response:

You can use a simple for loop:

list_strings =["john", "sarah", "bianca", "savie", "sandy", "john", "harry", "john", "debra", "john"]
result = []
for i, j in enumerate(list_strings):
    if j == "john":
        if i:
            result.append(list_strings[i-1])
        else:
            result.append(None)
[None, 'sandy', 'harry', 'debra']

CodePudding user response:

Here is how you an use the built-in zip method:

list_strings =["john", "sarah", "bianca", "savie", "sandy", "john", "harry", "john", "debra", "john"]

s = "john"

print([i for i, j in zip(list_strings[:-1], list_strings[1:]) if j == s])

Output:

['sandy', 'harry', 'debra']

In order to include the "none" for when the first string in the list is "john", you can do:

list_strings =["john", "sarah", "bianca", "savie", "sandy", "john", "harry", "john", "debra", "john"]

s = "john"

result = []
if list_strings[0] == "john":
    result.append("none")
for i, j in zip(list_strings[:-1], list_strings[1:]):
    if j == s:
        result.append(i)
print(result)

Output:

['none', 'sandy', 'harry', 'debra']

CodePudding user response:

There are porbably a thousand ways of doing that. One might be using a list comprehension and enumerate as

def get_before(search_name:str, names:list[str]) -> list[str]:
    return [names[i-1] if i > 0 else 'none' for i, name in enumerate(names) if name == search_name]

get_before('john', list_string)
  •  Tags:  
  • Related