【问题标题】:Counting the most common element in a 2D List in Python在 Python 中计算二维列表中最常见的元素
【发布时间】:2019-08-17 09:03:22
【问题描述】:

我正在寻找一种方法来计算 2D 列表中的出现次数。例如我有一个这样的列表:

[[John, 3],[Chris, 3],[Bryan,5],[John,3],[John,7]]

作为输出,我想计算 John 最常见的数字是什么

Most common number for the John is: 3

我用

轻松完成了所有名称
Counter(my_list[1]).most_common(5)

有人有建议吗?

【问题讨论】:

    标签: python python-3.x list counter


    【解决方案1】:

    这应该可行。

    from collections import Counter
    main_list = [['John', 3],['Chris', 3],['Bryan',5],['John',3],['John',7]] #your_list
    new_list = [i[1] for i in main_list if i[0]=='John']
    print(Counter(new_list).most_common(1)[0][0])
    

    【讨论】:

      【解决方案2】:

      我可能会在对输入数据进行查询之前对其进行重新整形。也许名称与值:

      name_lookup = defaultdict(list)
      for name, value in my_list:
          name_lookup[name].append(value)
      
      name = 'John'
      most_common, _ = Counter(name_lookup[name]).most_common(1)[0]
      print(f"Most common number for {name} is: {most_common}")
      

      【讨论】:

        【解决方案3】:

        您还可以进行过滤和映射:

        my_list = [['John', 3],['Chris', 3],['Bryan',5],['John',3],['John',7]]
        
        print(Counter(map(lambda y: y[1], filter(lambda x: x[0] == "John", my_list))).most_common(1))
        

        【讨论】:

          【解决方案4】:

          如果您 100% 确定每个名称总是有确切的 1 最频繁的元素,您可以按名称选择 sort,按名称选择 groupby,然后按以下方式使用 statistics.mode

          import itertools
          import statistics
          some_data = [['John', 3],['Chris', 3],['Bryan',5],['John',3],['John',7]]
          sorted_data = sorted(some_data,key=lambda x:x[0]) # sort by name
          most_frequent = {name:statistics.mode(j[-1] for j in list(data)) for name,data in itertools.groupby(sorted_data,key=lambda x:x[0])}
          print(most_frequent) # {'Bryan': 5, 'Chris': 3, 'John': 3}
          

          itertools.groupby 返回名称-数据对,但由于datas 本身包含键(在我们的例子中是名称)和值(在我们的例子中是数字),我们需要理解才能获得“原始”值。

          【讨论】:

            猜你喜欢
            • 2019-07-21
            • 2015-02-18
            • 2014-03-10
            • 2019-07-14
            • 2013-09-26
            • 1970-01-01
            • 2021-03-27
            • 1970-01-01
            相关资源
            最近更新 更多