Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python计数和组列表_Python_List - Fatal编程技术网

Python计数和组列表

Python计数和组列表,python,list,Python,List,这是我的代码: class distClass: dist = -1 #distance of current point from test point tag = '-' #tag of current point list =[] obj = distClass() # one record's distance and tag obj.dist = 1 obj.tag = 'F' list .append(obj) obj2 = distClass() # one

这是我的代码:

class distClass:
    dist = -1 #distance of current point from test point
    tag = '-' #tag of current point

list =[]
obj = distClass()  # one record's distance and tag
obj.dist = 1
obj.tag = 'F'
list .append(obj)
obj2 = distClass()  # one record's distance and tag
obj2.dist = 5
obj2.tag = 'F'
list .append(obj2)
obj3 = distClass()  # one record's distance and tag
obj3.dist = 10
obj3.tag = 'M'
list .append(obj3)
在此列表中,“F”存在2次 “M”存在1次

我需要得到存在最多的标签

(距离并不重要) 我不知道标签是什么,有多少种类型的标签

目标是了解列表中最重要的标记是什么

+--------------------+-----+
|      distance      | tag |
+--------------------+-----+
|  2.23606797749979  |  F  |
|  3.3166247903554   |  M  |
| 5.744562646538029  |  F  |
| 5.744562646538029  |  M  |
|        18.0        |  M  |
| 21.095023109728988 |  F  |
| 22.090722034374522 |  M  |
| 23.08679276123039  |  M  |
| 39.02563260217571  |  M  |
+--------------------+-----+ 

这是在对原始问题进行任何重大修改之前写的。当问题仅仅是“我需要计算发生了多少次
x.tag

from collections import Counter

class distClass:
    def __init__(self, dist=-1, tag='-'):
        self.dist = dist #distance of current point from test point
        self.tag = tag #tag of current point

my_list = []
my_list.append(distClass(1, 'F')) # one record's distance and tag
my_list.append(distClass(5, 'F')) # one record's distance and tag
my_list.append(distClass(10, 'M')) # one record's distance and tag

counts = Counter([o.tag for o in my_list])
print(counts.most_common(2))
这应该统计列表元素
.tag
的不同出现次数,然后继续打印两个最常见的元素


我还花了一些时间简化了代码,因为它表明您不需要处理单个变量
obj2
等,如果您只将它们存储在列表中,并且如果您不需要访问实例,只需执行
my_list[1]即可
。我将
distClass
的默认值移动到构造函数中。

创建标记列表,并在所述列表上使用
Counter()
。类似于
的单行计数器([o.tag代表列表中的o])
应该可以工作。另外,永远不要调用变量
列表或其他内置项,这会破坏东西。到目前为止,您尝试了什么?通过循环实现的简单方法似乎很简单。解决这个问题有什么具体的技术问题?目标表没有标记排序?这是一个“敏捷”问题:-)