Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đếm số key duy nhất cho giá trị trong danh sách Tuple Python

Sử dụng collections.defaultdict(int) để đếm tần suất xuất hiện của các tuple (coi như key) trong list lồng nhau.

Ví dụ

import collections

my_result = collections.defaultdict(int)
my_list = [[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
print("Danh sách:", my_list)

for elem in my_list:
    my_result[elem[0]] += 1

print("Kết quả:", my_result)

Kết quả

Danh sách: [[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
Kết quả: defaultdict(, {('Hello', 'Hey'): 2, ('Jane', 'Will'): 1, ('William', 'John'): 1, ('z', 'q'): 1})

Giải thích

  • Import collections.
  • Duyệt list, lấy phần tử đầu (tuple) làm key, tăng đếm.
  • In defaultdict.