【问题标题】:Finding the most common element in a list of variable-length tuples在可变长度元组列表中查找最常见的元素
【发布时间】:2019-10-12 07:46:14
【问题描述】:

我正在编写一个代码,它返回公交路线中最常见的公交站号(来自 csv 文件)。每行“bus_routes.csv”的第一个条目是路线名称,其余条目是公交车站号。

def most_common_number(routes):
    routes = load_routes('bus_routes.csv')
    bus_stop_ID = [col[1:] for col in routes]
    return max(sum(set((bus_stop_ID, []), key = sum(bus_stop_ID, []).count)

当我运行这段代码时,它返回一个错误; TypeError:只能将列表(不是“元组”)连接到列表 type(bus_stop_number) 是一个列表,所以我在最后一个代码中找不到元组的位置。

【问题讨论】:

  • 你可能需要 collections.Countermost_common 来代替你的代码,这听起来像可怕的复杂性。但我们没有你的数据。一个小样本会比我们没有的 csv 文件好得多
  • 你有多少列? col[1:] 可能会返回一个元组。单独打印并验证。然后像 Jean 说的那样使用 collections.Counter。
  • 这显然不是你的实际代码; set 不接受 key 参数(或任何关键字参数),并且括号不平衡。

标签: python list data-structures tuples counter


【解决方案1】:

我在上一个代码中找不到元组的位置

bus_stop_ID 的每个元素都是元组。

回顾一下,你有一个可变长度元组的列表,你想找到整个结构中最常见的元素。

这听起来像是 collections.Counter 的完美用法:

>>> from collections import Counter
>>> bus_stop_ID = [('id1', 'id2', 'id3'), ('id1',), ('id1', 'id3', 'id5')]
>>> [(stop_id, count)] = sum(map(Counter, bus_stop_ID), Counter()).most_common(1)
>>> stop_id
'id1'
>>> count
3

这里:

  • map(Counter, bus_stop_ID) 分别统计每条路线的公交站号;
  • sum(..., Counter()) 汇总跨路线的计数;
  • .most_common(1) 返回聚合计数中最常见的公交车站 ID(作为包含由公交车站 ID 及其计数组成的 2 元组的单元素列表)。

另一种方法是先连接所有路由(使用sum()),然后进行计数:

>>> [(stop_id, count)] = Counter(sum(bus_stop_ID, ())).most_common(1)

这更短但效率较低,因为它需要将所有路由连接成一个(可能是巨大的)元组。

一种——有点花哨——避免这种低效率的方法是使用itertools.chain()

>>> Counter(itertools.chain(*bus_stop_ID)).most_common(1)
[('id1', 3)]

这只是遍历第一条路线中的所有公交车站 ID,然后是第二条路线,依此类推,沿途进行计数。

出于好奇,我在任意选择的 10,000 个元组列表上对所有三种方法进行了基准测试,结果非常有趣:

In [11]: %timeit sum(map(Counter, bus_stop_ID), Counter()).most_common(1)
1 loop, best of 3: 235 ms per loop

In [12]: %timeit Counter(sum(bus_stop_ID, ())).most_common(1)
1 loop, best of 3: 2.64 s per loop

In [13]: %timeit Counter(itertools.chain(*bus_stop_ID)).most_common(1)
10 loops, best of 3: 17.3 ms per loop

【讨论】:

    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2017-06-14
    相关资源
    最近更新 更多