0

Here is an example of a list that I would like to convert into a list of lists in python:

p=[1,2,3,4]

I wrote the following code to address the problem:

u=[]
v=[x for x in p]
u.append(v)

my result: [[1,2,3,4]]

Result I would like to have: **[[1],[2],[3],[4]]**

Any suggestions? thanks.

4

3 回答 3

6

只需对您的列表理解做一个小调整,然后将x括号括起来以将每个元素放入列表中。

>>> p = [1, 2, 3, 4]
>>> v = [[x] for x in p]
>>> v
[[1], [2], [3], [4]]
于 2013-09-17T15:55:48.477 回答
2

你想要这样的东西:

u = [[x] for x in p]
于 2013-09-17T15:56:32.413 回答
1

正如其他答案所描述的那样,列表理解是一种简单的方法,但还有其他选择

>>> map(list,zip(p))
[[1], [2], [3], [4]]

或者

>>> from itertools import izip
>>> map(list,izip(p))
[[1], [2], [3], [4]]
于 2013-09-17T15:58:02.953 回答