MechEE
MechEE

Reputation: 27

Get a smaller list of lists from a list of lists of equal length based on criteria using Python

Good evening,

I have a table in the format of a list of lists. Each list is of the same length. I would like to obtain a smaller list based on the unique values of the numbers (1 list per number whichever shows up first).

tbl = [[1, 'aaa'], [2, 'aab'], [3, 'aac'], [4, 'GGC'], [4, 'GGH'], [6, 'GGS'], [7, 'aad']]

I've tried the following snippet of code:

tbl_simple = [list(x) for x in set(tuple(x) for x in tbl)]

But this line treats the whole list as one big unique value and I end up with the same table. I would like to filter on just the condition of the number (or some column of my choosing). The final result would look like this:

[[1, 'aaa'], [2, 'aab'], [3, 'aac'], [4, 'GGC'], [6, 'GGS'], [7, 'aad']]

Thank you for any assistance.

Upvotes: 0

Views: 60

Answers (1)

Bharel
Bharel

Reputation: 26901

An easy non-one liner would be:

output = []
seen = set()
for num, letters in tbl:
    if num in seen:
        continue
    output.append([num, letters])
    seen.add(num)

Still thinking about a one-liner.

Upvotes: 1

Related Questions