简体   繁体   English

如何计算列表中嵌套列表/字典较多的给定字符串的出现?

[英]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.

相关问题 numpy-如何按索引计算嵌套列表中项目的出现? - numpy - how do I count the occurrence of items in nested lists by index? 在遍历包含嵌套字典和列表的字典列表时,如何选择特定值? - How do I pick specific values as I iterate through a list of dictionaries that contain nested dictionaries and lists? 如何在字典列表中迭代嵌套字典? - How do I iterate through nested dictionaries in a list of dictionaries? 如何使用 Python 计算嵌套字典 in.json 文件中某个项目的出现次数(并可能迭代)? - How can I count occurrence of an item in nested dictionaries in .json file using Python (and possibly iterate over)? 如何计算 Python 中字符串列表中每个项目的出现次数? - How do I count the occurrence of each item from a list in a string in Python? 如何将字符串读入词典列表? - How do I read a string into a list of dictionaries? 如何从嵌套列表创建字典列表 - how to create a list of dictionaries from nested lists 计算列表列表中列表的出现次数 - count occurrence of a list in a list of lists 如何将字典列表转换为Python中的列表字典? - How do I convert a list of dictionaries to a dictionary of lists in Python? 如何根据 dataframe 中的条件计算字符串值的出现次数? - How do I count the occurrence of string values based on a condition in a dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM