python集合?

Python016

python集合?,第1张

*事先说明:以下代码及结果来自本设备Python控制台,在不同设备上可能结果有区别,望自己尝试为妙

集合(set),是一种Python里的(class),

集合类似于列表(list)可更改可迭代(iterable),但是元素不重复

定义集合使用花括号{},例如

>>>s = {"apple", "banana", "strawberry", "watermelon"}

警告!!!如果使用空括号

>>>a = {}

>>>a.__class__

<class 'dict'>

a将成为一个字典

想要定义空集合,

请使用类名。

>>>a = set()

类名定义也可以把迭代转换为集合:

>>>b = set("abc")

>>>b

{'a', 'b', 'c'}

但是,保存后它是无序的。

>>>s

{'banana', 'watermelon', 'strawberry', 'apple'}

(结果仅供参考,在不同设备上略有不同)

下面介绍它的性质:

1. 可更改:

使用add(x)方法添加元素x

>>>s.add("lemon")

>>>s

{'banana', 'strawberry', 'lemon', 'watermelon', 'apple'}

使用update(iter1, iter2, …)方法添加多个可迭代对象(如列表,元组(tuple),另一个集合)里的元素:

>>>s.update(("orange", "grape"))

>>>s

{'banana', 'strawberry', 'orange', 'lemon', 'watermelon', 'apple', 'grape'}

警告!!!如果使用字符串,字符串也会被迭代:

>>>a = set()

>>>a.update("apple")

>>>a

{'a', 'p', 'e', 'l'}

使用remove(x)移除元素x,如果x不存在,则抛出KeyError错误

>>>s.remove("lemon")

>>>s

{'banana', 'strawberry', 'orange', 'watermelon', 'apple', 'grape'}

>>>s.remove("cat")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

  s.remove("cat")

KeyError: 'cat'

使用discard(x)移除元素x,不会发生错误

>>>s.discard("grape")

>>>s

{'banana', 'strawberry', 'orange', 'watermelon', 'apple'}

>>>s.discard("dog")

>>>s

{'banana', 'strawberry', 'orange', 'watermelon', 'apple'}

2. 可迭代:

>>>for x in s:

...    print(x)

banana

strawberry

orange

watermelon

apple

3. 可以使用 len 函数获取集合长度;

>>>len(s)

5

可以使用 in 关键字检查一个元素是否在集合内,将返回逻辑值(bool)

>>>"apple"  in s

True

>>>"candy" in s

False

4.集合具有不重复性,因此它会自动去重:

>>>c = set("Hello World!")

>>>c

{' ', 'e', 'l', 'H', '!', 'r', 'W', 'o', 'd'}

5. 集合的运算

>>>d = set("abcdef")

>>>e = set("efghij")

>>>d

{'c', 'e', 'a', 'b', 'f', 'd'}

>>>e

{'h', 'e', 'g', 'j', 'f', 'i'}

>>>d - e # 集合d去掉集合e含有的元素,或者说集合d包含而集合e不包含的元素(不改变原集合)

{'a', 'b', 'd', 'c'}

>>>d | e # 集合d,e的所有元素

{'c', 'e', 'h', 'g', 'a', 'b', 'j', 'f', 'd', 'i'}

>>>d &e # 集合d,e都包含的元素

{'f', 'e'}

>>>d ^ e # 不同时出现在集合d, e中的元素

{'c', 'g', 'h', 'a', 'b', 'j', 'd', 'i'}

注意!!!

字符串、列表通用的+和*不适用于集合

>>>"abc" + "def"

'abcdef'

>>>[1, 2, 3] + [4, 5, 6]

[1, 2, 3, 4, 5, 6]

>>>d + e

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

    d + e

TypeError: unsupported operand type(s) for +: 'set' and 'set'

>>>"a" * 5

'aaaaa'

>>>[1] * 3

[1, 1, 1]

>>>d*3

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

    d * 2

TypeError: unsupported operand type(s) for *: 'set' and 'int'

(作者的小观点:既然集合是不能重复的,那么乘以、重复是没有意义的)

======================================================

python中集合的概念与数学中集合的概念一致,一般用一对花括号或set进行定义,集合的元素可以是整数、浮点数、字符串或元组,但不能是列表、集合或字典。集合的定义有以下几种形式:

在数学中集合有并集、交集、差集、补集等操作,这些操作可以非常便捷地用python实现。

集合还有一些常用的操作函数或方法: