Python中二维数组中的集合操作

是否可以在 python 中对二维数组使用集合操作。例如,


>>> a = [['a', 's'], 

         ['a', 'b'], 

         ['a', 's']]

>>> print(set(a))

Traceback (most recent call last):                                                                                                               

File "main.py", line 5, in <module>                                                                                                            

print(set(a))                                                                                                                                

TypeError: unhashable type: 'list'

它显示此错误。我需要一个输出{'a', 's'}, {'a', 'b'}。那么是否有可能以任何其他方法获得此输出。


慕姐4208626
浏览 217回答 2
2回答

犯罪嫌疑人X

先压平:a = [['a', 's'],&nbsp;&nbsp; &nbsp; &nbsp;['a', 's'],&nbsp;&nbsp; &nbsp; &nbsp;['a', 's']]print(set(y for x in a for y in x))&nbsp; # {'a', 's'}编辑:从更新的问题中,先将其转换为元组,然后将最终输出转换为集合。请注意,集合并不总是像原始值那样排列。a = [['a', 's'],&nbsp;&nbsp; &nbsp; ['a', 'b'],&nbsp;&nbsp; &nbsp; ['a', 's']]print([set(y) for y in set(tuple(x) for x in a)])&nbsp; # [{'a', 's'}, {'a', 'b'}]

慕的地10843

根据您的澄清评论,您显然是在寻找不同的列表。list对象在 Python 中不可散列,因为从本质上讲,它们是可变的,并且可以通过更改数据来更改它们的散列码。所以你想要/需要制作一个set可哈希对象。a = [['a', 's'],&nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ['a', 'b'],&nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ['a', 's']]>>> set(tuple(t) for t in a)&nbsp; # << unique tuples made of arrays in 'a'{('a', 's'), ('a', 'b')}>>> [list(x) for x in set(tuple(t) for t in a)] # << list of lists, will be unique by set(...)[['a', 's'], ['a', 'b']]>>> [set(x) for x in set(tuple(t) for t in a)] # << further, unique elements of the unique lists in a[{'s', 'a'}, {'b', 'a'}]但是由于散列问题,set您无法实现。lists
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python