Reputation: 412
I have a string, say:
s = "abcdefghi"
I need to create a list of lists of this such that the list formed will :-
list = [['a','b','c'],['d','e','f'],['g','h','i']]
Now the string can be anything but will always have length n * n
So if n = 4.
The len(s) = 16
And the list will be:
[['1','2','3','4'],['5','6','7','8'],...,['13','14','15','16']]
So each list in the list of lists will have length 4.
So I want to write a function which takes string and n as input and gives a list of list as output where the length of each list within the list is n.
How can one do this ?
UPDATE :
How can you convert the above list of list back to a string ?
So if l = list = [['a','b','c'],['d','e','f'],['g','h','i']]
How to convert it to a string :-
s = "abcdefghi"
I found a solution for this in stackoverflow :-
s = "".join("".join(map(str,l)) for l in list)
Thanks everyone !
Upvotes: 0
Views: 102
Reputation: 11476
Here's a list comprehension that does the job:
[list(s[i:i+n]) for i in range(0, len(s), n)]
If n * n == len(s)
is always true, then just put
n = int(len(s) ** 0.5) # Or use math.sqrt
For the edit part here's another list comprehension:
''.join(e for e in sub for sub in l)
Upvotes: 3
Reputation: 11075
I'm a personal fan of numpy...
import numpy as np
s = "abcdefghi"
n = int(np.sqrt(len(s)))
a = np.array([x for x in s], dtype=str).reshape([n,n])
Upvotes: 0
Reputation: 60944
from math import sqrt
def listify(s):
n = sqrt(len(s))
g = iter(s)
return [[next(g) for i in range(n)] for j in range(n)]
I like using generators for problems like this
Upvotes: 0