user1750444
user1750444

Reputation: 21

Uniquify all pairs in a python list

I've searched through post but can't find a solution for the exact problem I face. It's pretty easy but need a little guidance.

I have a python list that looks like:

lst = ['bob/sally', 'bob/chris', 'bob/nate', 'sally/bob', ...]

I want to iterate through and print only unique pairs. So in the above example, it would find that bob/sally is the same as sally/bob, so it would remove one.

Any help would be greatly appreciated! I've seen postings using set() and other python functions but I don't think that would work in this case.

Upvotes: 1

Views: 272

Answers (2)

Jon Clements
Jon Clements

Reputation: 142156

You could use a set, and normalise the order of names by sorting on them:

>>> data = ['bob/sally', 'bob/chris', 'bob/nate', 'sally/bob']
>>> set(tuple(sorted(item.split('/'))) for item in data)
set([('bob', 'chris'), ('bob', 'nate'), ('bob', 'sally')])

Or as has been pointed out by Ignacio Vazquez-Abrams and mgilson the use of a frozenset is much more elegant and eludes the sorting and tuple() step:

set(frozenset(item.split('/')) for item in data)

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798666

I've seen postings using set() and other python functions but I don't think that would work in this case.

Worked fine for me...

>>> set([frozenset((x, y)) for (x, y) in [('bob', 'sally'), ('bob', 'nate'), ('sally', 'bob')]])
set([frozenset(['bob', 'sally']), frozenset(['bob', 'nate'])])

Upvotes: 2

Related Questions