python集合长度函数 python集合常用函数( 二 )


但是,保存后它是无序的 。
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'}
de # 集合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集合长度函数和python集合常用函数的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

推荐阅读