【发布时间】:2015-01-20 14:37:13
【问题描述】:
我有一个嵌套列表,里面有重复项。我想获取每个列表内容及其相应的外观。所以对于嵌套列表,我有:
nested_list = [['time', 'company', 'language', 'price', 'description'],
['date', 'language', 'price', 'quantity'],
['time', 'company', 'language', 'price', 'description'],
['quantity', 'time', 'date', description']]
我使用了nested_list.sort(),它给出了:
['date', 'language', 'price', 'quantity']
['quantity', 'time', 'date', 'description']
['time', 'company', 'language', 'price', 'description']
['time', 'company', 'language', 'price', 'description']
因此,如果我希望将相同的项目(列表)放在一起,则一般排序可以正常工作。但是我怎样才能得到每个人的外观呢?我是否应该遍历整个列表并使用字典来记录每个嵌套列表的内容(字符串值,我确定我曾经在网上读过一些东西说列表不好用作字典键值)并计算它的外观?
无法使用普通的collections.Counter,因为TypeError: unhashable type: 'list'(如果列表用作哈希键,使用字典的另一个原因是个坏主意)。
有办法吗?我应该提取每个嵌套列表中的字符串值并使用长字符串作为键吗?
【问题讨论】:
-
请注意,您可以散列
tuple... 另请注意,“列表不适合用作字典键值” 因为你不能散列一个列表 - 字典键必须是不可变的,而列表不是,所以它不仅仅是“不好”它是不允许的。
标签: python list dictionary hash counter