繁体   English   中英

通过 Counter Python 对元组列表进行排序

[英]Sorting a tuple list by the Counter Python

我已阅读并尝试实施来自 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()

有一个更好的方法吗?

tuple包含不同的type

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

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

由于您想按出现次数计算,请尝试以下操作:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM