[英]Sorting a tuple list by the Counter Python
I have read and tried to implement suggestions from around Stack Overflow.我已阅读并尝试实施来自 Stack Overflow 的建议。
In Python 3.6+ I have a list of tuples that looks something like this:在 Python 3.6+ 中,我有一个看起来像这样的元组列表:
tuple_list=[(a=3,b=gt,c=434),(a=4,b=lodf,c=We),(a=3,b=gt,c=434)]
created by由...制作
for row in result:
tuple_list.append(var_tuple(row['d'], row['f'], row['q']))
I want to count the number of duplicates in the list and then sort the list so the number with the highest duplicates is at the top so I used我想计算列表中重复的数量,然后对列表进行排序,使重复次数最多的数字位于顶部,所以我使用了
tuple_counter = collections.Counter(tuple(sorted(tup)) for tup in tuple_list)
But this returns in error because但这会返回错误,因为
TypeError: unorderable types: int() < str()
I've also tried this but it doesn't seem to sort by the highest counter.我也试过这个,但它似乎没有按最高计数器排序。
tuple_counter = collections.Counter(tuple_list)
tuple_counter = sorted(tuple_counter, key=lambda x: x[1])
As well as this还有这个
tuple_counter = collections.Counter(tuple_list)
tuple_counter = tuple_counter.most_common()
Is there a better way to do this?有一个更好的方法吗?
tuple
contains different type
s tuple
包含不同的type
tuple_counter = collections.Counter(tuple(sorted(tup)) for tup in tuple_list)
This line errors saying that int < str
cannot be ordered.这行错误说
int < str
不能被排序。 before any of this is evaluated, the generator expression must be, and sorted(tup)
immediately breaks.在计算任何这些之前,生成器表达式必须是,并且
sorted(tup)
立即中断。 Why?为什么? From the error, I am confident that
tup
contains both integers and strings.从错误中,我确信
tup
包含整数和字符串。 You can't sort integers and strings in the same list because you can't compare an integer and a string with <
.你不能在同一个列表中对整数和字符串进行排序,因为你不能用
<
比较整数和字符串。 If you have a method of comparing int
s and str
s, try sorted(tup, key = function)
with your function to order int
s and str
s.如果您有比较
int
s 和str
s 的方法,请尝试使用sorted(tup, key = function)
与您的函数对int
s 和str
s 进行排序。
Since you want to count by the number of occurrences, try this:由于您想按出现次数计算,请尝试以下操作:
sorted_tuples = sorted(tuple_list, key = tuple_list.count)
This sorts the tuples using the counter function of tuple_list
as a key.这使用
tuple_list
的计数器函数作为键对元组进行排序。 If you want to sort descending, do sorted(tuple_list, key = tuple_list.count, reversed = True)
.如果要降序排序,请执行
sorted(tuple_list, key = tuple_list.count, reversed = True)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.