将列表作为单个元素插入元组

joa*_*avf 3 python python-2.7

我想从几个不同的元素创建一个元组,其中一个是列表,但我希望在创建元组时将此列表转换为单个元素.

a = range(0,10)
b = 'a'
c = 3
tuple_ex = (a,b,c)
Run Code Online (Sandbox Code Playgroud)

tuple_ex中存储的值为:([0,1,2,3,4,5,6,7,8,9],'a',3)

我希望存储在tuple_ex中的值是:(0,1,2,3,4,5,6,7,8,9,'a',3)

有一种简单的方法可以做到这一点,还是我需要编码?

Aja*_*234 9

您可以使用Python3的解包:

a = range(0,10)
b = 'a'
c = 3
t = (*a,b,c)
Run Code Online (Sandbox Code Playgroud)

输出:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3)
Run Code Online (Sandbox Code Playgroud)

对于Python2:

import itertools
t = tuple(itertools.chain.from_iterable([[i] if not isinstance(i, list) else i for i in (a, b, c)]))
Run Code Online (Sandbox Code Playgroud)

输出:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3)
Run Code Online (Sandbox Code Playgroud)