'Print next element of a list, if it matches the previous element
I have a list with similar elements, and I want to print the next element if I match the previous one. So something like this:
my_list=['one', 'two', 'one', 'one', 'two']
for ml in my_list:
if ml =='one':
print (next)
so the output would be:
two
two
Solution 1:[1]
Try this:
my_list=['one', 'two', 'one', 'one', 'two']
i = 0
for ml in my_list:
if ml =='one' and i!=(len(my_list)-1):
print (my_list[i+1])
i+=1
Output:
two
one
two
[Finished in 0.0s]
Solution 2:[2]
This code should do what you want:
my_list=['one', 'two', 'one', 'one', 'two']
for i, item in enumerate(my_list):
if i != 0:
if item == my_list[i-1]:
print(my_list[i+1])
Solution 3:[3]
I guess you are looking to print only two
. So you need to check if the next value is also not one
.
my_list=['one', 'two', 'one', 'one', 'two']
for i, ml in enumerate(my_list):
if ml =='one' and my_list[i+1] != 'one':
print (my_list[i+1])
The output of this will be:
two
two
Solution 4:[4]
I would actually say a more elegant solution to this problem would be to first convert your list
of words into a string
' '.join(my_list)
and then split it on the word 'one' like so
my_string.split('one')
as this would give you a list of all the subsequent words after each 'one' .
>>> ['', ' two ', ' ', ' two']
In summary, a simple one-line solution would be:
' '.join(my_list).split('one')
Solution 5:[5]
You can use the zip
function to get adjacent pairs:
for a, b in zip(my_list[:-1], my_list[1:]):
if a == "one":
print(b)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | hhaefliger |
Solution 3 | Joe Ferndz |
Solution 4 | Mohammed Terry Jack |
Solution 5 | Ji?í Baum |