集合

2019-05-02  本文已影响0人  Vector_Wan

无序,元素唯一, 一般用于元素去重

定义一个集合

set1 = set()
print(set1)
print(type(set1))
set()
<class 'set'>
set1 = {1, 2, 3, 5, 4}
print(type(set1))
<class 'set'>

添删改查

添加

set.add( )

set1.add(8)
print(set1)
{1, 2, 3, 4, 5, 8}

删除

不存在会报错

set.remove()

set.pop() 随机删除集合中的元素(由于集合的无序性)

set.discard() 如果存在就直接删除,不存在就不进行任何操作

set1 = {1, 2, 3, 5, 4}
set1.remove(1)
print(set1)
{2, 3, 4, 5}
set1 = {1, 2, 3, 5, 4}
set1.remove(10)
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-1-8be039e36d7a> in <module>
      1 set1 = {1, 2, 3, 5, 4}
----> 2 set1.remove(10)


KeyError: 10
set1 = {1, 2, 3, 5, 4}
set1.pop()
print(set1)
{2, 3, 4, 5}
set1 = {1, 2, 3, 5, 4}
set1.discard(10)
print(set1)
{1, 2, 3, 4, 5}

集合解析

from random import randint
set1 = {randint(0, 20) for _ in range(20)}
print (set1)
{0, 2, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 19}

找到能能被三整除的

res = {x for x in set1 if x%3 == 0}
print(res)
{0, 6, 9, 12, 15}
上一篇 下一篇

猜你喜欢

热点阅读