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

Gán ID cho mỗi giá trị duy nhất trong danh sách Python

Gán ID cho các phần tử trong danh sách, đảm bảo giá trị trùng lặp có cùng ID.

Cách 1: enumerate() và OrderedDict.fromkeys()

from collections import OrderedDict
Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ", Alist)
list_ids = [{v: k for k, v in enumerate(OrderedDict.fromkeys(Alist))}[n] for n in Alist]
print("The list of ids : ", list_ids)

Kết quả: [0, 1, 2, 0, 3, 4, 4]

Cách 2: Dùng defaultdict

from collections import defaultdict
Alist = ['Mon','Tue','Wed','Mon',5,3,3]
print("The given list : ", Alist)
d_dict = defaultdict(lambda: len(d_dict))
list_ids = [d_dict[n] for n in Alist]
print("The list of ids : ", list_ids)

Kết quả: [0, 1, 2, 0, 3, 4, 4]