Python元組列表中第K列的乘積


當需要在一個元組列表中查詢第'K'列的乘積時,可以使用簡單的列表推導式和迴圈。

元組是一種不可變的資料型別。這意味著,一旦定義的值就不能透過訪問其索引元素來更改。如果嘗試更改元素,則會導致錯誤。它們很重要,因為它們確保只讀訪問。列表可以用來儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。

元組列表基本上包含包含在列表中的元組。

列表推導式是迭代列表並對其執行操作的簡寫。

下面是相同的演示 -

示例

線上演示

def prod_compute(my_val) :
   my_result = 1
   for elem in my_val:
      my_result *= elem
   return my_result

my_list = [(51, 62, 75), (18,39, 25), (81, 19, 99)]

print("The list is : " )
print(my_list)
print("The value of 'K' has been initialized")
K = 2

my_result = prod_compute([sub[K] for sub in my_list])

print("The product of the 'K'th Column of the list of tuples is : ")
print(my_result)

輸出

The list is :
[(51, 62, 75), (18, 39, 25), (81, 19, 99)]
The value of 'K' has been initialized
The product of the 'K'th Column of the list of tuples is :
185625

解釋

  • 定義了一個名為“prod_compute”的函式,它接受一個引數。
  • 一個變數初始化為1,並且引數被迭代。
  • 此元素與變數相乘。
  • 它作為輸出返回。
  • 定義了一個元組列表,並在控制檯上顯示。
  • 透過傳遞此元組列表來呼叫該函式。
  • 輸出顯示在控制檯上。

更新於:2021年3月11日

149 次檢視

啟動您的職業生涯

完成課程獲得認證

開始
廣告