5_Python进阶_set数据结构

set本身是一个集合的意思。
根据数学关于集合的定义可知,set里面的数据不能是重复的
实例:检查列表中包含重复的元素。

# 用for循环检索出不重复的元素/数据
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
outputs = []
for item in inputs:
    if inputs.count(item) > 1:
        if item not in outputs:
            outputs.append(item)
        else:
            pass
    else:
        pass
print(outputs)

输出结果是:

['red', 'yellow']

可见,用循环的方法检查列表中重复元素比较麻烦。
当采用set数据结构时候,会简洁一些。

# 采用set数据结构,简单一些
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
outputs = set([x for x in inputs if inputs.count(x) > 1])
# 列表里面逐个遍历inputs列表中重复的x值,因此列表里面是重复的,可以用set去掉重复
print(outputs)

输出结果是:

{
    
    'red', 'yellow'}

set数据结构也和数学上的集合类似,也有交集和差集操作。
交集:两个集合中都有的数据。
差集:⽤⼀个集合减去另⼀个集合的数据。

# set交集操作
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
inputs_also = ['yellow', 'brown']
# 首先要把list数据结构转换成set数据结构
inputs = set(inputs)
inputs_also = set(inputs_also)
print(inputs.intersection(inputs_also))

输出结果是:

{
    
    'yellow'}

可见,set.intersection()方法查找交集。

# set差集操作
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
inputs_also = ['yellow', 'brown']
# 首先要把list数据结构转换成set数据结构
inputs = set(inputs)
inputs_also = set(inputs_also)
print(inputs.difference(inputs_also))

可见,set.difference()方法查找差集。
set的创建:既可以用list创建,再用set()转换成set实例;也可以直接用花括号创建。

# set创建
set_instance = {
    
    'a', 15, 13.69, False}
print(type(set_instance))

输出结果是:

<class 'set'>

猜你喜欢

转载自blog.csdn.net/m0_48948682/article/details/125445382
今日推荐