Python – 字典值列表中以 K 开头的元素频率
有时在处理大量数据时,我们可能会遇到一个问题,即我们有字符串列表形式的数据,这些数据是字典键的值,我们希望计算以字符K 开头的元素的出现次数。让我们讨论一下这种方法的某些方法可以执行任务。
方法#1:使用循环+ startswith()
这是可以执行此任务的一种方式。在此,我们使用嵌套循环蛮力检查字典列表中的每个元素并增加计数器。
# Python3 code to demonstrate working of
# Element Frequency starting with K in dictionary value List
# using loop + startswith()
# initializing dictionary
test_dict = {1 : ['Gfg', 'is', 'for', 'Geeks'], 2 : ['Gfg', 'is', 'CS', 'God'], 3: ['Gfg', 'best']}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'G'
# Element Frequency starting with K in dictionary value List
# using loop + startswith()
res = 0
for sub in test_dict.values():
for ele in sub:
if ele.startswith(K):
res += 1
# printing result
print("The element frequency starting with K : " + str(res))
输出 :
The original dictionary is : {1: ['Gfg', 'is', 'for', 'Geeks'], 2: ['Gfg', 'is', 'CS', 'God'], 3: ['Gfg', 'best']}
The element frequency starting with K : 5
方法 #2:使用sum() + startswith()
这是可以执行此任务的另一种方式。在此,我们执行获取任务
使用 sum() 和生成器的频率用于在一行中执行展平逻辑。
# Python3 code to demonstrate working of
# Element Frequency starting with K in dictionary value List
# using sum() + startswith()
# initializing dictionary
test_dict = {1 : ['Gfg', 'is', 'for', 'Geeks'], 2 : ['Gfg', 'is', 'CS', 'God'], 3: ['Gfg', 'best']}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'G'
# Element Frequency starting with K in dictionary value List
# using sum() + startswith()
res = sum(ele.startswith(K) for ele in [sub for j in test_dict.values() for sub in j])
# printing result
print("The element frequency starting with K : " + str(res))
输出 :
The original dictionary is : {1: ['Gfg', 'is', 'for', 'Geeks'], 2: ['Gfg', 'is', 'CS', 'God'], 3: ['Gfg', 'best']}
The element frequency starting with K : 5