[英]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.