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.
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.
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.
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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With