开发者

Why am I getting an error using 'set' in Python?

s = set('ABC')
s.add('z')
s.开发者_JS百科update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')


As others pointed out, 'DEF', the set member you're trying to remove, is not a member of the set, and remove, per the docs, is specified as "Raises KeyError if elem is not contained in the set.".

If you want "missing element" to mean a silent no=op instead, just use discard instead of remove: that's the crucial difference between the discard and remove methods of sets, and the very reason they both need to exist!


The argument to set.remove() must be a set member.

'DEF' is not a member of your set. 'D' is.


From http://docs.python.org/library/stdtypes.html :

remove(elem)

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

'DEF' is not in the set


Do you expect 'DEF' to be treated as an element or a set?

In the latter case use s.difference_update('DEF').

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜