如何计算列表中唯一列表的数量? [英] How to count number of unique lists within list?

查看:60
本文介绍了如何计算列表中唯一列表的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Counter和itertools,但是由于列表不可用,所以它们不起作用.

I've tried using Counter and itertools, but since a list is unhasable, they don't work.

我的数据如下:[[1,2,3],[2,3,4],[1,2,3]]

My data looks like this: [ [1,2,3], [2,3,4], [1,2,3] ]

我想知道列表[1,2,3]出现过两次,但是我不知道该怎么做.我当时只是想将每个列表转换成一个元组,然后对其进行哈希处理.有更好的方法吗?

I would like to know that the list [1,2,3] appears twice, but I cant figure out how to do this. I was thinking of just converting each list to a tuple, then hashing with that. Is there a better way?

推荐答案

>>> from collections import Counter
>>> li=[ [1,2,3], [2,3,4], [1,2,3] ]
>>> Counter(str(e) for e in li)
Counter({'[1, 2, 3]': 2, '[2, 3, 4]': 1})

只要每个子列表中没有嵌套的可变项(例如[ [1,2,3], [2,3,4,[11,12]], [1,2,3] ]:

The method that you state also works as long as there are not nested mutables in each sublist (such as [ [1,2,3], [2,3,4,[11,12]], [1,2,3] ]:

>>> Counter(tuple(e) for e in li)
Counter({(1, 2, 3): 2, (2, 3, 4): 1})

如果子列表列表中确实嵌套了其他不可使用的类型,请使用strrepr方法,因为该方法也处理所有子列表.或以递归方式将其全部转换为元组(更多工作).

If you do have other unhasable types nested in the sub lists lists, use the str or repr method since that deals with all sub lists as well. Or recursively convert all to tuples (more work).

这篇关于如何计算列表中唯一列表的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆