Home > Enterprise >  Adding to set() if part of tuple not exists
Adding to set() if part of tuple not exists

Time:12-18

I would like to use something similar to the add() function to add tuples to a set. However, I want them not to be added if a part of that tuple already exists in the set.

For example:

mySet = set()
myList = [['A','B',1],['B','C',2],['C','D',3],['A','B',2]]

for i in myList:
    mySet.add(((i[0],i[1]),i[2]))

This gives me a result as:

mySet = (('A', 'B'), 1), (('A', 'B'), 2), (('B', 'C'), 2), (('C', 'D'), 3)

But I would like the ('A','B')-combination to only appear once (the first time it is added), so that my result is:

mySet = {(('A', 'B'), 1), (('B', 'C'), 2), (('C', 'D'), 3)}

CodePudding user response:

Why not use a dictionary in that case?

d = {}
for i,j,k in myList:
    if (i,j) not in d:
        d[(i,j)] = k
mySet = set(d.items())

As @Matthias suggests, reversed makes it even better:

mySet = set({(i,j): k for i,j,k in reversed(myList)}.items())

Output:

{(('A', 'B'), 1), (('B', 'C'), 2), (('C', 'D'), 3)}

CodePudding user response:

Transform the data to a dictionary first.

my_list = [['A','B',1],['B','C',2],['C','D',3],['A','B',2]]
my_dict = {tuple([*x[:2]]):x[2] for x in reversed(my_list)}
# alternative for the previous line: my_dict = {(x, y): z for x, y, z in reversed(my_list)}
print(my_dict)  # debug output
my_set = {*my_dict.items()}  # or: my_set = set(my_dict.items())
print(my_set)

Output for my_dict is {('A', 'B'): 1, ('C', 'D'): 3, ('B', 'C'): 2}.

The final set is {(('A', 'B'), 1), (('B', 'C'), 2), (('C', 'D'), 3)}.

According to your wanted output you want the first element from the list that matches the criteria. So we have to loop over the list backwards with reversed. Otherwise a later value would overwrite the first matching entry.

CodePudding user response:

before you append it to the set, try using set(list) so that all elements will be unique so there should be no repeating elements

  • Related