将[x,y]转换为[x] [y]的单独列表

时间:2017-04-06 21:42:01

标签: python

我试图将[x,y]转换为[x]和[y]

的两个列表

尝试以下代码:

a = [[[0.322, 0.219], [0.334, 0.159], [0.321, 0.139], [0.37, 0.068], 
[0.435, 0.222],[0.146, 0.152], [0.156, 0.027], [0.156, 0.19], [0.269, 
0.124], [0.239, 0.082], [0.22, 0.201]]]

from operator import itemgetter 
a1,b = map(itemgetter(0),a), map(itemgetter(1),a)
print(a1,b)
a1,b = map(list,a)

它给出以下错误:ValueError:解压缩的值太多(预期为2

4 个答案:

答案 0 :(得分:4)

这个怎么样:

a =[[0.322, 0.219], [0.334, 0.159], [0.321, 0.139], [0.37, 0.068], 
[0.435, 0.222],[0.146, 0.152], [0.156, 0.027], [0.156, 0.19], [0.269, 
0.124], [0.239, 0.082], [0.22, 0.201]]

b,c = map(list, zip(*a)))

b,c = list(zip(*a))

这应该也可以起作用:

b,c = zip(*a)

答案 1 :(得分:2)

你删除了一组额外的括号,你可以使用numpy:

import numpy as np

a = [[0.322, 0.219], [0.334, 0.159], [0.321, 0.139], [0.37, 0.068], 
[0.435, 0.222],[0.146, 0.152], [0.156, 0.027], [0.156, 0.19], [0.269, 
0.124], [0.239, 0.082], [0.22, 0.201]]

a = np.array(a)

print a

a = np.rot90(a)

print a[0]
print a[1]

>>>
[[ 0.322  0.219]
 [ 0.334  0.159]
 [ 0.321  0.139]
 [ 0.37   0.068]
 [ 0.435  0.222]
 [ 0.146  0.152]
 [ 0.156  0.027]
 [ 0.156  0.19 ]
 [ 0.269  0.124]
 [ 0.239  0.082]
 [ 0.22   0.201]]
[ 0.219  0.159  0.139  0.068  0.222  0.152  0.027  0.19   0.124  0.082
  0.201]
[ 0.322  0.334  0.321  0.37   0.435  0.146  0.156  0.156  0.269  0.239
  0.22 ]

docs https://docs.scipy.org/doc/numpy/reference/generated/numpy.rot90.html

然后返回列表格式:

x_list = a[0].tolist()
y_list = a[1].tolist()

答案 2 :(得分:0)

x = [item[0] for item in a[0]]
y = [item[1] for item in a[0]]

答案 3 :(得分:0)

您也可以使用理解将其拆分。

a = [[[0.322, 0.219], [0.334, 0.159], [0.321, 0.139], [0.37, 0.068], 
[0.435, 0.222],[0.146, 0.152], [0.156, 0.027], [0.156, 0.19], [0.269, 
0.124], [0.239, 0.082], [0.22, 0.201]]]

a1,b = [ i[0] for i in a[0]],[ i[1] for i in a[0]]

print(a1,b)

上面保留了原始问题的所有括号。如果您确实无意中有一个额外的设置,那么您可以使用它来构建列表

a1,b = [ i[0] for i in a],[ i[1] for i in a]