问题
So for sets you can do a symmetric difference (^) which is the equivalent of union minus intersection. Why is ^ an unsupported operand for Counter objects while union and intersection still work?
回答1:
Expanding on my comment, turns out it was discussed at time, and rejected.
Click the link for the full message (and its thread); I'll just quote the "high order bits" of Raymond Hettinger's reply:
It's unlikely that I will add this [symmetric difference] method to the Counter API because the rarity of use case does not warrant the added API complexity. IMO, adding a method like this makes the class harder to learn, understand and remember. It doesn't seem like much of a win over using the existing alternatives:
...
I would like to see someone post a subclass to the ASPN Cookbook that adds a number of interesting, though not common operations.
...
The Counter() class has low aspirations. It is a dictionary that fills-in missing values with zero and is augmented by a handful of basic methods for managing the counts.
Full message here:
https://mail.python.org/pipermail/python-list/2010-August/585040.html
There's also a recipe in the ASPN Cookbook implementing __xor__
in a Counter
subclass:
http://code.activestate.com/recipes/577362-extension-to-python-3-counter-class/
回答2:
For Counter objects, &
and |
don't mean intersection and union as they do for sets ... they mean max
and min
.
Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.
With these definitions, what would the ^
operator mean?
If you want the symmetric difference of the keys, you can do c1.viewkeys() ^ c2.viewkeys() 1
1on python3.x, use .keys()
instead
来源:https://stackoverflow.com/questions/38449289/why-is-there-no-symmetric-difference-for-collections-counter