Python - 元组列表中值的唯一键计数
pythonserver side programmingprogramming更新于 2025/10/20 18:20:17
当需要获取元组列表中唯一值的数量时,使用‘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’运算符获取唯一元素。
将其转换为列表,并将其长度分配给变量。
这是控制台上显示的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

