我有一份清单:
countall = [[5, 0], [4, 1], [4, 1], [3, 2], [4, 1], [3, 2], [3, 2], [2, 3], [4, 1], [3, 2], [3, 2], [2, 3], [3, 2], [2, 3], [2, 3], [1, 4], [4, 1], [3, 2], [3, 2], [2, 3], [3, 2], [2, 3], [2, 3], [1, 4], [3, 2], [2, 3], [2, 3], [1, 4], [2, 3], [1, 4], [1, 4], [0, 5]]
我想在上面的列表中找到子列表的频率。在
我尝试过使用itertools:
^{pr2}$但是,我得到了错误的结果:
[1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1]
我的列表理解有什么问题?在
Groupby似乎在处理一个接一个的序列。要使用它,您需要先对列表进行排序。另一个选择是使用Counter类:
输出:
^{pr2}$正如ForceBru指出的,首先对列表进行排序,然后使用groupby:
输出:
^{pr2}$您的代码有错误:
然后将每个单独的列表分组到
countall
中,这是不需要的。在你可以直接
groupby
排序(countall)另外,正如@Bemmu回答的那样,你可以使用集合。计数器. 但这不支持
list
,因此首先必须将数据转换为元组或字符串,然后使用Counter
如评论中所述,如果使用的是groupby,则需要进行排序。在
代码:
测试代码:
^{pr2}$结果:
相关问题 更多 >
编程相关推荐