我偶尔使用python,抱歉看似微不足道的问题
>>> a = set(((1,1),(1,6),(6,1),(6,6)))
>>> a
set([(6, 1), (1, 6), (1, 1), (6, 6)])
>>> a - set(((1,1)))
set([(6, 1), (1, 6), (1, 1), (6, 6)])
>>> a.remove((1,1))
>>> a
set([(6, 1), (1, 6), (6, 6)])
为什么'-
'运算符没有删除元素,但remove
呢?
答案 0 :(得分:8)
因为你错过了一个逗号:
>>> set(((1,1)))
set([1])
应该是:
>>> set(((1,1),))
set([(1, 1)])
或者,为了更具可读性:
set([(1,1)])
甚至(Py2.7 +):
{(1,1)}
答案 1 :(得分:2)
在尝试指定一个元素的元组时,您错过了一个逗号。元组的语法确实有些棘手......
一些例子
w = 1, 2, 3 # creates a tuple, no parenthesis needed
w2 = (1, 2, 3) # works too, like x+y is the same as (x+y)
x, y, z = w # unpacks a tuple
k0 = () # creates an empty tuple
k1 = (1,) # a tuple with one element (note the comma)
k = (1) # just a number, NOT a tuple
foo(1, 2, 3) # call passing three numbers, not a tuple
bar((1, 2, 3)) # call passing a tuple
if x in 1, 2: # syntax error, parenthesis are needed
pass
for x in 1, 2: # ok here
pass
gen = (x for x in 1, 2) # error, parenthesis needed here around (1, 2)