Python 程式用於從元組列表中找出所有元素都能被 K 整除的元組


當需要查詢元素可被某個特定元素“K”整除的元組時,可以使用列表解析。

以下是對其進行演示的示例 −

示例

 即時演示

my_list = [(45, 90, 135), (71, 92, 26), (2, 67, 98)]

print("The list is : ")
print(my_list)

K = 45
print("The value of K has been initialized to ")
print(K)
my_result = [sub for sub in my_list if all(ele % K == 0 for ele in sub)]

print("Elements divisible by K are : " + str(my_result))

輸出

The list is :
[(45, 90, 135), (71, 92, 26), (2, 67, 98)]
The value of K has been initialized to
45
Elements divisible by K are: [(45, 90, 135)]

說明

  • 定義一個元組列表,並顯示在控制檯上。

  • 定義 K 的值,並顯示在控制檯上。

  • 使用列表解析遍歷元素。

  • 檢查元組列表中的每個元素是否可被 K 整除。

  • 如果可被 K 整除,則將其轉換為列表元素,並存儲在變數中。

  • 這將作為輸出顯示在控制檯上。

更新於: 15-4-2021

746 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告