python中的一组列表列表

2023-07-03Python开发问题
11

本文介绍了python中的一组列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个列表列表:

mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]]

我想转换成 set,即删除重复列表并从中创建一个新列表,其中仅包含 unique 列表.

and I want to convert into a set i.e. remove the repeating lists and creating a new list out of it which will only contain the unique lists.

在上述情况下,所需的答案将是

In above case the required answer will be

[[1,2,3],[4,5,6],[7,8,9]]

但是当我执行 set(mat) 时,它给了我错误

But when I do set(mat), it gives me error

TypeError: unhashable type: 'list'

TypeError: unhashable type: 'list'

你能解决我的问题吗?提前致谢!

Can you please solve my problem. Thanks in advance!

推荐答案

由于列表是可变的,它们不能被散列.最好的办法是将它们转换为元组并形成一个集合,像这样

Since the lists are mutable, they cannot be hashed. The best bet is to convert them to a tuple and form a set, like this

>>> mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]]
>>> set(tuple(row) for row in mat)
set([(4, 5, 6), (7, 8, 9), (1, 2, 3)])

我们遍历 mat,一次一个列表,将其转换为一个元组(它是不可变的,所以 sets 很酷)和生成器被发送到 set 函数.

We iterate through the mat, one list at a time, convert that to a tuple (which is immutable, so sets are cool with them) and the generator is sent to the set function.

如果您希望将结果作为列表列表,您可以通过将 set 函数调用的结果转换为列表来扩展相同的列表,如下所示

If you want the result as list of lists, you can extend the same, by converting the result of set function call, to lists, like this

>>> [list(item) for item in set(tuple(row) for row in mat)]
[[4, 5, 6], [7, 8, 9], [1, 2, 3]]

这篇关于python中的一组列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10