4

我有一个字符串数组,例如:

a = ['123', '456', '789']

我想把它拆分成一个二维字符数组:

b = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

我在用着

[[element for element in line] for line in array]

实现我的目标但发现它不容易阅读,是否有任何内置函数或任何可读的方式来做到这一点?

4

5 回答 5

10

Looks like a job for map:

>>> a = ['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Relevant documentation:

于 2012-12-11T03:08:17.233 回答
4

you could do something like:

first_list = ['123', '456', '789']
other_weirder_list = [list(line) for line in first_list]

Your solution isn't that bad, but you might do something like this or the map suggestion by arashajii.

于 2012-12-11T03:07:24.730 回答
3

map(list, array) should do it.

于 2012-12-11T03:08:29.017 回答
1

You can use map:

>>> a
['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Although I really don't see why you'd need to do this (unless you plan on editing one specific character in the string?). Strings behave similarly to lists.

于 2012-12-11T03:08:18.817 回答
0

首先我尝试了e.split(''),但我得到了ValueError: empty separator

尝试这个:

a = ['123', '456', '789']
b = [list(e) for e in a]
b
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
于 2013-07-10T16:35:17.617 回答