简体   繁体   中英

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.

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)

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'])])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM