0

I am having a hard time merging the elements within the Python list according to a given number.

I already found the solution to work on with a certain number. But I want to work with a variety of given number(N).

i.e. When I have a list

['There', 'was', 'a', 'farmer', 'who', 'had', 'a', 'dog', 'and', 'cat', '.']

Result,

When N = 2

['There was', 'a farmer', 'who had', 'a dog', 'and cat', '.']

or N = 3

['There was a', 'farmer who had', 'a dog and', 'cat .']

I would much prefer that it modified the existing list directly, not used any module or library.

Any help is greatly appreciated!!

20am847
  • 7
  • 4
  • 1
    Can you show some code what you have tried? – Arghya Saha Apr 13 '19 at 16:41
  • Possible duplicate: https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks just `' '.join` the chunks – juanpa.arrivillaga Apr 13 '19 at 16:42
  • "I would much prefer that it modified the existing list directly, not used any module or library." Why would you prefer those things? If you want to modify the list directly, it almost certainly will be inefficient. And why don't you want to use a module? – juanpa.arrivillaga Apr 13 '19 at 16:42

3 Answers3

0

Here's the sensible way to do it. it does create a new list. Since that is more efficient than trying to modify the original

a = ['There', 'was', 'a', 'farmer', 'who', 'had', 'a', 'dog', 'and', 'cat', '.']
n = 2
print([' '.join(a[i:i+n]) for i in range(0, len(a), n)])
n = 3
print([' '.join(a[i:i+n]) for i in range(0, len(a), n)])

Output:

['There was', 'a farmer', 'who had', 'a dog', 'and cat', '.']
['There was a', 'farmer who had', 'a dog and', 'cat .']
rdas
  • 20,604
  • 6
  • 33
  • 46
0

This is the simplest way I can remember of:

my_list = ['a','b','c','d','e','f','g','h','i']
N = 3

my_list[0:N] = [''.join(my_list[0:N])]
Miguel
  • 1,295
  • 12
  • 25
0
    word_list = ['There', 'was', 'a', 'farmer', 'who', 'had', 'a', 'dog', 'and', 'cat', '.']
    new_word_list = []
    N = int(input())
    for i in range(0, len(word_list), N):
        string = ''
        for j in (range(len(word_list) - i) if len(word_list) - i < N else range(N)):
            string = string + word_list[i + j] + ' '
         new_word_list.append(string)

     print(new_word_list)

Here I implemented it using basic for loops to iterate over the list, although new list had to be created.

Rahul
  • 576
  • 1
  • 5
  • 9