2 回答
TA贡献2080条经验 获得超4个赞
先压平:
a = [['a', 's'],
['a', 's'],
['a', 's']]
print(set(y for x in a for y in x)) # {'a', 's'}
编辑:从更新的问题中,先将其转换为元组,然后将最终输出转换为集合。请注意,集合并不总是像原始值那样排列。
a = [['a', 's'],
['a', 'b'],
['a', 's']]
print([set(y) for y in set(tuple(x) for x in a)]) # [{'a', 's'}, {'a', 'b'}]
TA贡献1785条经验 获得超8个赞
根据您的澄清评论,您显然是在寻找不同的列表。
list对象在 Python 中不可散列,因为从本质上讲,它们是可变的,并且可以通过更改数据来更改它们的散列码。所以你想要/需要制作一个set可哈希对象。
a = [['a', 's'],
... ['a', 'b'],
... ['a', 's']]
>>> set(tuple(t) for t in a) # << 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
添加回答
举报
