jsguy
jsguy

Reputation: 2179

How can I remove the duplicates in a column of a 2D list and return the result as another list?

I read some data from a file. Each line of the file contains 10 numbers and I save all the lines in a 2 dimensional list.

data = []
with open(args.input, 'r') as f:
   for line in itertools.islice(f, 0, None):
    items = line.split()[1:]
    data.append(items)

Now I want to remove the duplicates of the first column in this 2d list and return the results as a list.

Is there some function that can do this or should I implement it myself?

thank you in advance!

edit after comment by Tichodroma:

Sample input:

1 2 3 1 1 9 9 9 9 9
1 1 1 1 1 1 1 1 1 1
2 2 3 3 3 3 3 3 3 3
3 2 3 3 3 3 3 3 3 3
2 3 3 4 3 3 2 3 4 3

first column contains [1 1 2 3 2]

I want [1 2 3]

the order doesn't matter.

Upvotes: 0

Views: 39

Answers (1)

user1907906
user1907906

Reputation:

data = """1 2 3 1 1 9 9 9 9 9
1 1 1 1 1 1 1 1 1 1
2 2 3 3 3 3 3 3 3 3
3 2 3 3 3 3 3 3 3 3
2 3 3 4 3 3 2 3 4 3"""

col1 = [line.split()[0] for line in data.splitlines()]
# col1 == ['1', '1', '2', '3', '2']

print(set(col1))

Output:

{'1', '2', '3'}

Upvotes: 1

Related Questions