Ask Your Question
1

What is the quickest method for eliminating identical items in a two-dimensional list by changing elements within the sublists?

asked 2023-07-15 03:43:27 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-15 03:56:02 +0000

scrum gravatar image

One method is to convert the list of lists into a set of tuples, where each tuple represents a sublist. Since sets can only contain unique elements, this will automatically remove any duplicate sublists. Then, the set can be converted back into a list of lists. Here's an example code:

lst = [[1, 2], [3, 4], [1, 2], [5, 6], [3, 4]]
lst_set = set(tuple(sublist) for sublist in lst)
new_lst = [list(tple) for tple in lst_set]
print(new_lst)
# Output: [[1, 2], [3, 4], [5, 6]]

In this example, the original list lst contains two identical sublists: [1, 2] and [3, 4]. After converting the list to a set of tuples and back to a list of lists, the duplicates have been removed, and new_lst only contains [1, 2], [3, 4], and [5, 6].

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-15 03:43:27 +0000

Seen: 9 times

Last updated: Jul 15 '23