我有以下元组(list_permutation):
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
我想将其转换为如下所示的列表:
[[1],[2],[3],[1,2],[1,3]]...
这是我已经尝试过的代码:
result = [int(x) for x, in list_permutation]
print(result)
但是我遇到了这个错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-63-fc7f88d67875> in <module>
----> 1 result = [int(x) for x, in list_permutation]
2 print(result)
<ipython-input-63-fc7f88d67875> in <listcomp>(.0)
----> 1 result = [int(x) for x, in list_permutation]
2 print(result)
ValueError: too many values to unpack (expected 1)
答案 0 :(得分:4)
l = [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
new_l = [list(x) for x in l]
print(new_l)
这将产生[[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
。
答案 1 :(得分:0)
您可以使用内置的地图功能:
l = [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
l = list(map(list, l))
print(l)
这应该给你
[[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
答案 2 :(得分:0)
使用地图可以轻松实现
perm = [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
perm_as_list = map(list, perm)
下面的输出
In [1]: perm = [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
In [2]: perm_as_list = map(list, perm)
In [3]: perm_as_list
Out[3]: [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
答案 3 :(得分:0)
list函数可以将元组转换为list 您有一个元组列表,所以如下:
list_permutation=[(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
result = [list(x) for x in list_permutation]