python与集合的操作

时间:2012-10-07 06:17:29

标签: python

我偶尔使用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呢?

2 个答案:

答案 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)