python中的set类型

一. 定义

set是一个无序且不重复的元素集合

set和dict类似,是一组key的集合,但不存储value

set有以下特性:

1. 由于key不能重复,所有set中没有重复的key

2. 元素为不可变对象(不能将可变类型字典或者列表作为元素)

二. 创建set

1. 直接使用{}创建新的set并初始化

set1 = {1, 2, 3, (4, 5, 6), "good news"}

2. 使用set关键字来创建

set2 = set([1, 2, 3])                 #相当于set2 = {1, 2, 3}, set函数只能传入一个参数
set3 = set((1,2,3))                  #相当于set3 = {1,2,3}
set4 = set({'a':1,'b':2,'c':3})       #相当于set4 = {'a','b','c'}

3. 创建空的set

如果要创建一个空的set,只能使用set()关键字,因为如果使用set1={}这种方式,那么set1会被声明为一个空的字典

三. 基本操作

1. 重复的操作在set中自动被过滤

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}

2. 通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果

>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

3. 通过 remove(key) 方法可以删除元素

>>> s = {1, 2, 3, 4}
>>> s.remove(4)
>>> s
{1, 2, 3}

4. 两个set可以做数学意义上的交集、并集等操作

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

四. 练习

给定一个只包含正整数且非空的数组,返回该数组中重复次数最多的前N个数字(返回结果按重复次数从多到少降序排列,N不存在取值非法的情况)

a=[1,6,7,4,4,5,4,5,4,5,5,6,7,8,5,6,7,3,4,2,2,1,4,8,9,4,5,6]

def get_datas(a):
    result = []
    data_dict = {}
    #键值对:键——数字,值——在列表中的次数
    #set(a)将列表转化为set类型,并过滤掉其中重复的数字
    for item in set(a):
        data_dict[str(item)] = a.count(item)

    #将键值对按值(数字出现的次数)排序——从高到低排序
    #sorted为临时性排序,不会改变原列表data_dict的顺序
    res = sorted(data_dict.values(), reverse=True)
    for num in res:
        for key, value in data_dict.items():
            #key not in result能保证相同的数字只添加一次
            if num == value and key not in result:
                result.append(key)
    return result

result = get_datas(a)
print(result)

运行结果

['4', '5', '6', '7', '8', '2', '1', '3', '9']

参考文章

https://www.cnblogs.com/whatisfantasy/p/5956775.html

https://www.cnblogs.com/shijiusui/p/7748523.html

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143167793538255adf33371774853a0ef943280573f4d000

猜你喜欢

转载自www.cnblogs.com/cnhkzyy/p/9296282.html
今日推荐