简体   繁体   中英

Convert a string into list of list

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 !

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)

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])
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM