Python将列表转换为元组和列表的列表

Python convert list to a list of tuple & tuple to list of tuple

如何转换列表

1
    [1, 2, 3, 4, 5]

到元组列表

1
    [(1, 2, 3, 4, 5)]

和转换元组

1
    (1, 2, 3, 4, 5)

到元组列表

1
    [(1, 2, 3, 4, 5)]


试试看!

1
2
3
l=[1, 2, 3, 4, 5]
t=tuple(i for i in l)
t

输出:

1
(1, 2, 3, 4, 5)

1
2
tl = [t]
tl

输出:

1
[(1, 2, 3, 4, 5)]

做以下工作怎么样?

1
2
your_list = [1,2,3,4]
new_list = [tuple(your_list)]

在第二种情况下:

1
2
your_tuple = (1,2,3,4)
new_list = [your_tuple]


1
2
3
4
arr = [1, 2, 3, 4]
print(arr)
tpl = (arr,)
print(type(tpl), tpl)

输出:

1
2
[1, 2, 3, 4]
<class 'tuple'> ([1, 2, 3, 4],)

案例2:

1
2
3
4
tpl_2 = (1, 2, 3, 4)
print(tpl_2)
arr_2 = [tpl_2]
print(type(arr_2), arr_2)

输出:

1
2
(1, 2, 3, 4)
<class 'list'> [(1, 2, 3, 4)]

来自列表:

1
[tuple(x)]

从元组:

1
[x]

1
2
3
4
5
6
>>> x = [1,2,3]
>>> [tuple(x)]
[(1, 2, 3)]
>>> x = (1, 2, 3)
>>> [x]
[(1, 2, 3)]