在 Python 中使用引數初始化元組


當需要使用某些引數初始化元組時,可以使用 'tuple' 方法和 '*' 運算子。

'tuple' 方法會將傳入給它的可迭代物件轉換成元組類型別。

* 運算子可用於獲得兩個值的乘積。它還可用於多次乘以一個值並將它顯示在控制檯上。

以下是針對它的演示 −

示例

線上演示

N = 6
print("The value of N has been initialized to "+str(N))

default_val = 2
print("The default value has been initialized to " +str(default_val))

indx = 3
print("The index value has been initialized to "+ str(indx))

val_to_add = 6
print("The value to be added is initialized to " +str(val_to_add))

my_result = [default_val] * N
my_result[indx] = val_to_add
my_result = tuple(my_result)

print("The tuple formed is : ")
print(my_result)

輸出

The value of N has been initialized to 6
The default value has been initialized to 2
The index value has been initialized to 3
The value to be added is initialized to 6
The tuple formed is :
(2, 2, 2, 6, 2, 2)

說明

  • 初始化值 'N'、'index'、'需要新增的值' 和一個預設值並顯示在控制檯上。
  • 預設值乘以 'N' 並分配給一個變數。
  • 此操作分配給一個變數。
  • 該變數的 'index' 被分配了需要新增的值。
  • 接下來,該變數被轉換成一個元組,並存儲在變數中。
  • 此變數就是顯示在控制檯上的輸出。

更新於:12-3-2021

413 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告