[英]How do I count the occurrence of a given string in list that has more nested lists/dictionaries?
During a technical phone screen, I was given a list similar to below and asked to count the number of times the string 'a' occurs: 在技术电话屏幕上,为我提供了类似于以下的列表,并要求计算字符串'a'出现的次数:
input = ['a', 'b', ['a', 'b', {'a': ['b', 'a', [{'b': ['a', 'b', {'a': 'a'}]}]]}]]
As you can see, in addition to the 'a' being an item in the list, it can also be an item in nested lists, as well as the keys and/or values in nested dictionaries. 如您所见,除了“ a”是列表中的一项之外,它还可以是嵌套列表中的一项,以及嵌套字典中的键和/或值。
This is the code I have so far in Python: 这是我到目前为止在Python中拥有的代码:
def count_letter_a(arr):
count = 0
for item in arr:
if item == 'a':
count += 1
elif isinstance(item, list):
count_letter_a(item)
elif isinstance(item, dict):
for k, v in item.items():
pass
return count
I'm stuck on what to do with the handling of dictionary keys/values portion of my function. 我一直在处理函数的字典键/值部分。 What do I need to do?
我需要做什么?
You can just add the 'a'
count of keys and values, or simple recursively apply it to the items directly. 您可以仅添加键和值的
'a'
计数,或者简单地将其直接递归地应用于项目。 This requires that you count occurrences in tuples
as well (I included sets
to complete the built-in collections): 这要求您还计算
tuples
出现次数(我提供了一些sets
来完成内置集合):
def count_a(obj):
if isinstance(obj, (list, tuple, set)):
return sum(map(count_a, obj))
if isinstance(obj, dict):
return sum(map(count_a, obj.items()))
if obj == 'a':
return 1
return 0
>>> x = ['a', 'b', ['a', 'b', {'a': ['b', 'a', [{'b': ['a', 'b', {'a': 'a'}]}]]}]]
>>> count_a(x)
7
You're really close! 你真的很亲密!
def count (x):
if isinstance (x, list):
return sum (count (y) for y in x)
elif isinstance (x, dict):
return sum (count ([ k, v ]) for k,v in x.items ())
elif x == "a":
return 1
else:
return 0
It works like this 它像这样工作
count ('foo')
# 0
count ([ 'a', 'b', 'c' ])
# 1
count (['a', 'b', ['a', 'b', {'a': ['b', 'a', [{'b': ['a', 'b', {'a': 'a'}]}]]}]])
# 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.