Questions about Python set

Asked 1 years ago, Updated 1 years ago, 118 views

aList = [1, 2, [1 ,2], 'c', [1, 2] ]

I know that the set function removes duplicate values from the list

Nested list, and if it's a mixed list of characters

When using the set function, an error was printed as unsashable. I was wondering if I could solve the problem by converting the list into a tuple I'm thinking of changing the list to a tuple, using the set function, and then changing it to the original form I'm trying.

list(set([tuple(set(item)) for item in aList]))

I have a question because there is an error that 'int' object is not usable.

python set list-comprehension

2022-09-21 10:19

3 Answers

The list is a changeable type, so it cannot be used as a hash.

Try it with the following.

set(tuple(i) if type(i) == list else i for i in aList)


2022-09-21 10:19

If the item is 1, an error will occur in the set.


2022-09-21 10:19

It's too long. I don't know if you intended this, but....

[list(x) if isinstance(x, tuple) else x for x in set([tuple(i) if isinstance(i, list) else i for i in aList ])]


2022-09-21 10:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.