列印所有元素頻率大於 K 的行


當需要列印所有元素的頻率都大於 K 的行時,可以定義一個方法,它採用兩個引數,並使用“all”運算子和迭代來給出結果。

以下是它的演示 −

示例

def frequency_greater_K(row, K) :
   return all(row.count(element) > K for element in row)
my_list = [[11, 11, 32, 43, 12, 23], [42, 14, 55, 62, 16], [11, 11, 11, 11], [42, 54, 61, 18]]
print("The tuple is :")
print(my_list)
K = 1
print("The value of K is :")
print(K)
my_result = [row for row in my_list if frequency_greater_K(row, K)]
print("The result is :")
print(my_result)

輸出

The tuple is :
[[11, 11, 32, 43, 12, 23], [42, 14, 55, 62, 16], [11, 11, 11, 11], [42, 54, 61, 18]]
The value of K is :
1
The result is :
[[11, 11, 11, 11]]

說明

  • 定義了一個名為“frequency_greater_K”的方法,它將行和 K 值作為引數,並返回元素計數和鍵之間的比較作為輸出。

  • 定義並顯示了列表。在控制檯上顯示列表。

  • 使用列表解析來迭代列表,並在每個列表上呼叫該方法。

  • 此結果將賦值給一個變數。

  • 這是顯示在控制檯上的輸出。

更新於: 2021-09-07

121 次瀏覽

啟動你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.