In Python is augmented addition of sets are not supported?
In the Python开发者_StackOverflow社区 sets, why augmented removal of elements are supported but addition is not supported?
For example if s
is a mutable set:
s = set(['e', 'd', 'h', 's'])
s -= set('ds')
gives s = set(['e', 'h'])
but this does not work for s += set('pk')
and results in TypeError
.
The correct syntax for what you want to do is
s |= set('ds')
For sets, the binary operators |
, &
and ^
are used for union, intersection and symmetric difference, respectively. I guess the reason +
is not considered a valid set operation is because it is not used in set theory, while -
is.
There's a nice symmetry between the way these three binary operators work on integers and the way they work on sets:
set("1234") & set("1456") == set(['1', '4'])
bin(0b111100 & 0b100111) == '0b100100'
# 1234 1 456 1 4
set("14") | set("456") == set(['1', '5', '4', '6'])
bin(0b100100 | 0b000111) == '0b100111'
# 1 4 456 1 456
set("14") ^ set("456") == set(['1', '5', '6'])
bin(0b100100 ^ 0b000111) == '0b100011'
# 1 4 456 1 56
You could use s | set('ds')
, assuming s = set('edhs')
First of all python tutorial is your the very best friend and contains all information you need. You can take a look at the following link to get more info about python set types: http://docs.python.org/release/2.7/library/stdtypes.html?highlight=set.difference#set-types-set-frozenset
You can use set union method for this purpose:
union(other, ...) is the same as set | other | ...
Return a new set with elements from the set and all others.
baseSet = set('abcd')
baseSet = baseSet.union('zx')
Or using set update method:
update(other, ...) is the same as set |= other | ...
Update the set, adding elements from all others.
baseSet = set('abcd')
baseSet.update('zx')
精彩评论