【问题标题】:Sorting a tuple list by the Counter Python通过 Counter Python 对元组列表进行排序
【发布时间】:2018-03-09 01:49:48
【问题描述】:

我已阅读并尝试实施 Stack Overflow 周围的建议。

在 Python 3.6+ 中,我有一个看起来像这样的元组列表:

tuple_list=[(a=3,b=gt,c=434),(a=4,b=lodf,c=We),(a=3,b=gt,c=434)]

创建者

for row in result:    
    tuple_list.append(var_tuple(row['d'], row['f'], row['q']))

我想计算列表中重复的数量,然后对列表进行排序,使重复次数最多的数字位于顶部,所以我使用了

tuple_counter = collections.Counter(tuple(sorted(tup)) for tup in tuple_list)

但这会返回错误,因为

TypeError: unorderable types: int() < str()

我也试过这个,但它似乎没有按最高计数器排序。

tuple_counter = collections.Counter(tuple_list)
tuple_counter = sorted(tuple_counter, key=lambda x: x[1])

还有这个

tuple_counter = collections.Counter(tuple_list)
tuple_counter = tuple_counter.most_common()

有没有更好的方法来做到这一点?

【问题讨论】:

  • 你在第 1 行有语法错误,我没有投反对票,但你应该显示一个有效的tuple_list 我们可以使用
  • 等等,为什么tuple_counter.most_common() 不起作用?
  • @JaredGoguen 因为sorted(tup) 在您获得tuple_counter 之前就失败了方式。看我的回答。
  • @HyperNeutrino ???那个是由collections.Counter(tuple_list) 实例化的,它不使用排序...
  • @JaredGoguen 这都是猜测,除非问题被编辑,我投票关闭

标签: python python-3.x list sorting tuples


【解决方案1】:

tuple 包含不同的types

tuple_counter = collections.Counter(tuple(sorted(tup)) for tup in tuple_list)

这行错误说不能订购int &lt; str。在计算任何一个之前,生成器表达式必须是,并且sorted(tup) 立即中断。为什么?从错误中,我确信tup 包含整数和字符串。您无法对同一列表中的整数和字符串进行排序,因为您无法将整数和字符串与&lt; 进行比较。如果您有比较 ints 和 strs 的方法,请尝试将 sorted(tup, key = function) 与您的函数一起订购 ints 和 strs。

既然你想按出现次数来计算,试试这个:

sorted_tuples = sorted(tuple_list, key = tuple_list.count)

这使用tuple_list 的计数器函数作为键对元组进行排序。如果要降序排序,请执行sorted(tuple_list, key = tuple_list.count, reversed = True)

【讨论】:

    猜你喜欢
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多