Python计数和组列表

2024-09-29 21:43:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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  |
+--------------------+-----+ 

Tags: andofobjdisttag标签recordone
1条回答
网友
1楼 · 发布于 2024-09-29 21:43:57

这是在对原始问题进行任何重大修改之前写的。当问题仅仅是“我需要数一数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的默认值移动到构造函数中

相关问题 更多 >

    热门问题