Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the next element of list in Python

Tags:

python

list

I have a list of sentences like:

lst = ['A B C D','E F G H I J','K L M N']

What i did is

l = []
for i in lst:
    for j in i.split():
        print(j)
        l.append(j) 

first = l[::2]
second = l[1::2]

[m+' '+str(n) for m,n in zip(first,second)]

The Output i got is

lst = ['A B', 'C D', 'E F', 'G H', 'I J', 'K L', 'M N']

The Output i want is:

lst = ['A B', 'B C','C D','E F','F G','G H','H I','I J','K L','L M','M N']

I am struggling to think how to achieve this.

like image 233
james joyce Avatar asked Jul 23 '19 15:07

james joyce


People also ask

How do you get the next value in Python?

Python next() Function The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.

Can I use next on a list in Python?

Python next() method returns the next element from the list; if not present, prints the default value. If the default value is not present, raise the StopIteration error. You can add a default return value to return if the iterable has reached its end.

How do you get the next element in a for loop?

Use enumerate() function to access the next item in a list in python for a loop. The for loop allows to access the variables next to the current value of the indexing variable in the list.


2 Answers

First format your list of string into a list of list, then do a mapping by zip.

i = [i.split() for i in lst]

f = [f"{x} {y}" for item in i for x,y in zip(item,item[1::])]

print (f)

#['A B', 'B C', 'C D', 'E F', 'F G', 'G H', 'H I', 'I J', 'K L', 'L M', 'M N']
like image 99
Henry Yik Avatar answered Oct 14 '22 07:10

Henry Yik


Your problem is that you're flattening the whole list and dividing to couples when you want to divide to subsequent couples only the inner elements. So for that we will perform the operation on each element separatly:

lst = ['A B C D','E F G H I J','K L M N']

res = []
for s in lst:
    sub_l = s.split()
    for i in range(len(sub_l)-1):
        res.append("{} {}".format(sub_l[i], sub_l[i+1]))
print(res)

Gives:

['A B', 'B C', 'C D', 'E F', 'F G', 'G H', 'H I', 'I J', 'K L', 'L M', 'M N']
like image 38
Tomerikoo Avatar answered Oct 14 '22 07:10

Tomerikoo