Python - 每个键的唯一值计数
给定一个字典列表,任务是编写一个Python程序来计算每个键的唯一值。
例子:
Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6},
{“gfg” : 7, “is” : 3, “best” : 10}]
Output : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Explanation : gfg has 1 and 7 as unique elements, hence 2.
Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6},
{“gfg” : 1, “is” : 3, “best” : 10}]
Output : {‘gfg’: 1, ‘is’: 1, ‘best’: 3}
Explanation : gfg has only 1 as unique element, hence 1.
方法 #1:使用len() + set() + 循环
在这种情况下,使用 set() 提取唯一值,使用 len() 获取其计数,然后将结果映射到使用 keys() 提取的每个键。迭代键发生在循环中。
Python3
# Python3 code to demonstrate working of
# Unique values count of each Key
# Using len() + set()
# initializing lists
test_list = [{"gfg": 1, "is": 3, "best": 2}, {
"gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
for key in test_list[0].keys():
# mapping unique values.
res[key] = len(set([sub[key] for sub in test_list]))
# printing result
print("Unique count of keys : " + str(res))
Python3
# Python3 code to demonstrate working of
# Unique values count of each Key
# Using len() + set() + dictionary comprehension
# initializing lists
test_list = [{"gfg": 1, "is": 3, "best": 2}, {
"gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]
# printing original list
print("The original list is : " + str(test_list))
# dictionary comprehension for compact solution
res = {key: len(set([sub[key] for sub in test_list]))
for key in test_list[0].keys()}
# printing result
print("Unique count of keys : " + str(res))
输出:
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},
{‘gfg’: 7, ‘is’: 3, ‘best’: 10}]
Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
方法 #2:使用字典理解 + len() + set()
与上述方法类似,不同之处在于字典理解被用作速记的一种线性替代方法。
蟒蛇3
# Python3 code to demonstrate working of
# Unique values count of each Key
# Using len() + set() + dictionary comprehension
# initializing lists
test_list = [{"gfg": 1, "is": 3, "best": 2}, {
"gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]
# printing original list
print("The original list is : " + str(test_list))
# dictionary comprehension for compact solution
res = {key: len(set([sub[key] for sub in test_list]))
for key in test_list[0].keys()}
# printing result
print("Unique count of keys : " + str(res))
输出:
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},
{‘gfg’: 7, ‘is’: 3, ‘best’: 10}]
Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}