Python 程式以統計元組列表中值的唯一鍵


如果需要獲取元組列表中值的唯一鍵計數,則可以對其進行迭代並確定各個計數。

下面是對其的演示 −

示例

 即時演示

import collections
my_result = collections.defaultdict(int)

my_list = [[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
print("The list of list is :")
print(my_list)
for elem in my_list:
   my_result[elem[0]] += 1
print("The result is : ")
print(my_result)

輸出

The list of list is :
[[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
The result is :
defaultdict(<class 'int'>, {('Hello', 'Hey'): 2, ('Jane', 'Will'): 1, ('William', 'John'): 1, ('z', 'q'): 1})

說明

  • 匯入所需的包。

  • 定義包含字串和字元的元組列表。

  • 將列表顯示在控制檯上。

  • 對列表進行迭代,並將第一個元素增加 1。

  • 此結果顯示在控制檯上。

更新時間:2021 年 4 月 15 日

109 次瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告