Python - 元组列表中值的唯一键计数
当需要获取元组列表中唯一值的计数时,使用“defaultdict”、“set”运算符和“append”方法。
示例
以下是相同的演示-
from collections import defaultdict
my_list = [(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)]
print("名单是:")
print(my_list)
my_result = defaultdict(list)
for element in my_list:
my_result[element[1]].append(element[0])
my_result = dict(my_result)
result_dictionary = dict()
for key in my_result:
result_dictionary[key] = len(list(set(my_result[key])))
print("结果列表是:")
print(result_dictionary)输出结果名单是:
[(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)]
结果列表是:
{32: 2, 21: 3, 11: 1, 10: 1, 23: 2}解释
所需的包被导入到环境中。
元组列表被定义并显示在控制台上。
创建了一个空字典。
遍历列表,并将第二个和第一个元素附加到字典中。
此列表再次转换为字典。
创建了另一个空字典。
遍历列表,并使用“set”运算符获取唯一元素。
它被转换为一个列表,并将其长度分配给一个变量。
这是显示在控制台上的输出。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短