Python: best way to find out from which set the results of `symmetric_difference` are from?

StackOverflow https://stackoverflow.com/questions/18102319

문제

What is the best practice for finding out from which set the results of symmetric_difference are from?

intersect = s1.symmetric_difference(s2)

The result should look like

{'34':'s1', '66':'s2'} 

Where '34','66' are the unique items.

도움이 되었습니까?

해결책

To do this most cleanly, the following should work:

intersect = s1.symmetric_difference(s2)
result = dict([(i, ("s1" if i in s1 else "s2")) for i in intersect])

다른 팁

{x : 's1' for x in intersect if x in s1} + {x : 's2' for x in intersect if x in s2}

or

{x : ('s1' if x in s1 else 's2') for x in intersect}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top