Set comprehensions in Python and testing for membership in the set being created -


this question semantics of set comprehensions, first need explain context. i'm trying create new set of tuples paired value in touple unique regardless of order of values in pair. simplifying actual program, have {(1, 2), (2, 1), (3, 4)} , i'd {(1, 2), (3, 4)}

i tried doing this:

oldset = {(1, 2), (2, 1), (3, 4)}  newset = set() newset = {(val1, val2) (val1, val2) in oldset if not (val2, val1) in newset} 

however, newset {(1, 2), (2, 1), (3, 4)}, implying wrong conditional expression. understanding of comprehensions suggests above syntactic sugar this:

newset =  set() (val1, val2) in oldset:   if not (val2, val1) in newset:     newset.add((val1, val2)) 

this traditional looping structure works (newset {(1, 2), (3, 4)}). there comprehensions causes conditional evaluated before newset has members? i'm new python, i'm wondering if there's subtle i'm missing.

thanks!

you misunderstood; set comprehension distinct expression, separate assignment. expression produces new set() object assigned newset, replacing old set() object had.

as such, iterate , build set, previous , separate set() object bound newset remains empty. in reality, set comprehension this:

newset = set() _result = set() (val1, val2) in oldset:     if not (val2, val1) in newset:         result.add((val1, val2)) newset = _result 

you use side effects alter separate set iterate:

seen = set() newset = {(val1, val2) (val1, val2) in oldset           if not ((val2, val1) in seen or seen.add((val1, val2))} 

this uses seen track has been processed , includes tuple if both conditions true:

  • the inverse has not been seen before,
  • the seen.add() operation tuple returns false value. since seen.add() returns none, going case.

note builds same set twice, may regular loop , done it:

newset = set() (val1, val2) in oldset:     if not (val2, val1) in newset:         newset.add((val1, val2)) 

since tuples consist of 2 values only, may use sorting here; pair of tuples (a, b), (b, a) has 1 unique sorting, after all:

newset = {tuple(sorted(t)) t in oldset} 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -