0

Say, I have this list: ['1', '1', '0', '1', '1', '1', '0', '0', '0', '0', '1', '0']

My expected output: [['1', '1', '0', '1'], ['1', '1', '0', '0'], ['0', '0', '1', '0']]

I got the expected output this way:

from collections import deque as de
a = '110111000010'
a = list(a)
que = de(a)
a = []
l = []
n = 0
while que:
    item = que.popleft()
    l.append(item)
    n += 1
    if n == 4:
        a.append(l)
        n = 0
        l = []
print(a)

I wanted to know is there a more efficient and simpler way to achieve this which can be described as elegant, understandable and most importantly pythonic.

Anaam
  • 124
  • 6
  • You don't have to convert string to list. You can slice and dice the string just like a list. Hint: Use `range` to iterate through a chunk of the string and convert that chunk to a list to get the desired output. – Shiva Jan 08 '21 at 11:23

1 Answers1

0
def  func(arr, size):
    l = []
    for i in range(0, len(arr), size):
        l.append(arr[i:i+size])
    return l

arr = ['1', '1', '0', '1', '1', '1', '0', '0', '0', '0', '1', '0']
n = 4

sol = func(arr, n)
print(sol)

output

[['1', '1', '0', '1'], ['1', '1', '0', '0'], ['0', '0', '1', '0']]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44