I have read and tried to implement suggestions from around Stack Overflow.
In Python 3.6+ I have a list of tuples that looks something like this:
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_counter = collections.Counter(tuple(sorted(tup)) for tup in tuple_list)
This line errors saying that int < str
cannot be ordered. before any of this is evaluated, the generator expression must be, and sorted(tup)
immediately breaks. Why? From the error, I am confident that tup
contains both integers and strings. 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.
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. If you want to sort descending, do sorted(tuple_list, key = tuple_list.count, reversed = True)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.