1

我只是偶尔使用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

4

2 回答 2

8

因为你错过了一个逗号:

>>> set(((1,1)))
set([1])

应该:

>>> set(((1,1),))
set([(1, 1)])

或者,为了更具可读性:

set([(1,1)])

甚至(Py2.7+):

{(1,1)}
于 2012-10-07T06:19:45.553 回答
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)
于 2012-10-07T06:43:33.140 回答