简体   繁体   English

将字符串转换为列表列表

[英]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 现在,字符串可以是任何东西,但总长为n * n

So if n = 4. 因此,如果n = 4.

The len(s) = 16 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. 因此,列表列表中的每个列表的长度都为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. 所以我想编写一个函数,将字符串和n作为输入,并给出一个列表列表作为输出,其中列表中每个列表的长度为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']] 因此,如果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 :- 我在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 * n == len(s)始终为真,则将

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... 我是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 我喜欢使用发电机来解决这样的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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