【发布时间】: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