[Solved] Python – get unique and sorted values in list of lists [closed]


Since your question does not clearly state that: This anwer assumes that the entries in all list should be sorted afterwards and that each number is unique within each sublist.

You can reach this as follows:

numbers = [[50, 100],[100, 130],[20, 50, 100, 130]]

unique = sorted({n for l in numbers for n in l})

new_numbers = [[x if x in l else 0 for x in unique] for l in numbers]

new_numbers
> [[0, 50, 100, 0], [0, 0, 100, 130], [20, 50, 100, 130]]

Some explanation on the solution: First, get all (unique) numbers that occur in the original list. Then, go through the original list and add 0 to places, where a number from the unique numbers is not part of the sublist. Note that during this operation, the original list will be sorted, so [100, 50] will become [0, 50, 100, 0].

edit: made more pythonic due to juanpa.arrivillaga’s comment.

7

solved Python – get unique and sorted values in list of lists [closed]