【问题标题】:The key of the dict in the python array is the most frequentpython数组中dict的key是最频繁的
【发布时间】:2021-07-17 08:03:14
【问题描述】:

我有一个数组,里面有一些字典。

虽然下面的方法可以实现。

但是我必须对返回的值做更多的处理,我认为这很糟糕。

有没有更好的办法?

data = [{'name': 'A'},
        {'name': 'A'},
        None,
        None,
        {'name': 'B'},
        {'name': 'B'},
        {'name': 'B'}]
process = list(map(lambda x: x.get('name') if isinstance(x, dict) else None, data))
result = max(process, key=process.count)

for _ in data:
    if isinstance(_, dict) and _['name'] == result:
        array_index = _
        break

print(data.index(array_index))

{'name':'B'} 出现次数最多。

数据数组{'name':'B'}在哪里?

根据上面的例子,我想得到4

但是上面的代码又要被for循环处理一遍,我觉得很不好。

【问题讨论】:

  • 还有更优雅的 wat,例如使用 itertools 或转换为 Pandas 系列并使用 count_values(),但它们都像普通循环一样工作。实际上,我认为如果不检查所有列表项,您将无法做到。
  • 使用 2 个单独的 for 循环不会影响解决方案的时间复杂度。最后O(kn) = O(n)

标签: python python-3.x list dictionary


【解决方案1】:

嘿,我用 github copilot 看看它是如何解决这个问题的

def get_index_of_most_frequent_dict_value(data):
    """
    Return the index of the most frequent value in the data array
    """
    # Create a dictionary to store the frequency of each value
    frequency = {}
    for item in data:
        if item is None:
            continue
        if item['name'] in frequency:
            frequency[item['name']] += 1
        else:
            frequency[item['name']] = 1

    # Find the most frequent value
    most_frequent_value = None
    most_frequent_value_count = 0
    for key, value in frequency.items():
        if value > most_frequent_value_count:
            most_frequent_value = key
            most_frequent_value_count = value

    # Find the position of the most frequent value
    for i in range(len(data)):
        if data[i] is None:
            continue
        if data[i]['name'] == most_frequent_value:
            return i

输出:

4

时间对比:

My solution (a): 5.499999999998562e-06 seconds
Your solution (b): 7.400000000004625e-06 seconds

a < b?是的

【讨论】:

  • 数据中出现频率最高的是{'name':'B'},我需要的是{'name':'B'}在数组中的位置。
  • 我也可以像你这样写一个方法来解决问题,但我想要的是不使用for循环是否能得到我想要的答案。
  • 不过多写一个方法,代码还是很长。我不喜欢它。
  • Copilot 也重写了代码以找到{'name': 'B']} 的位置。抱歉,函数太长了,但它对您的解决方案来说更快更简单。我会看看你是否可以在没有 for 循环的情况下做到这一点。
  • 我认为没有 for 循环你无法解决这个问题。
【解决方案2】:

你可以这样做

import ast
data = [{'name': 'A'},
        {'name': 'A'},
        None,
        None,
        {'name': 'B'},
        {'name': 'B'},
        {'name': 'B'}]
x={str(y):data.count(y) for y in data}
j=ast.literal_eval(max (x))
print(j)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2012-06-13
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多