3 回答

TA貢獻1878條經驗 獲得超4個贊
在 Python 中創建一個元組就像將你需要的東西放在一個括號中的元組中一樣簡單:
my_tuple = (1, 2, 3)
a = 1
b = 2
c = 3
another_tuple = (a, b, c) # also works with variables, or anything else with a value
如果你想要在元組中的東西是可以解包的其他東西,比如列表或元組本身,你可以使用解包運算符*將它解包到新的元組中:
a = 1
b = [2,3,4]
c = 5
my_tuple = (a, *b, c)
不是您的問題,但請注意,您也可以在不使用*運算符的情況下從元組中獲取內容,因為它隱含在賦值語句中:
x, _, z = my_tuple # continued from before
在此示例中,a( 1) 中的內容現在也在其中,x而 中的內容c也在 中z。元組中b和第二個位置的內容被丟棄(這就是_這里下劃線的意思,“不在乎”。)
如果您明確需要解包并且正在構建一些新變量,或者需要單獨元組的元素,它們也可以用作元組,則可以使用解包運算符。例如,調用函數時:
a_tuple = ('Hi there', 'John')
def greeting(phrase='Hello', name='world'):
print(f'{phrase}, {name}!')
greeting(*a_tuple)
在這個例子中,調用greetingasgreeting(a_tuple)會給你帶來非常討厭的結果('Hi there', 'John'), world!,顯然不是你想要的,但你仍然可以使用帶有 unpack 操作符的元組。
另一個明顯的例子是解決 OP 問題的例子。

TA貢獻1831條經驗 獲得超4個贊
其中一種方式如下圖所示
from functools import reduce
import operator
# create a bunch of lists, reduce them to one list and finally convert to tuple
result = tuple(reduce(operator.add, ([a], b, [c])))
print(result)
添加回答
舉報