当前位置:   article > 正文

python 字典与集合详解_python 字典是集合

python 字典是集合

字典&集合

一、基础

    字典:是一系列由健和值配对组成的元素的集合。在python3.7+版本中字典是有序的,在3.6之前是无序的

    集合:和字典基本相同,唯一的区别在于集合没有键和值的配对,是一系列无序的、唯一的元素组合

  • 基础方法(键和值都是混合类型)
# 创建
# 字典创建
d1 = {'name':'liuyi','age':18,'gender':'male'}
d2 = dict({'name':'liuyi','age':18,'gender':'male'})
d3 = dict([('name','liuyi'),('age',18),('gender','male')])
d4 = dict(name='liuyi',age=18,gender='male')
d1==d2==d3==d4
#输出:true

# 集合创建
s1 = {1,2,3}
s2 = set([1,2,3])
s1 == s2
#输出:true

# 访问
# 字典访问
d = {'name':'liuyi','age':18,'gender':'male'}
d['name']
# 输出:'liuyi'
d['dd']
# 输出:KeyError: 'dd'

# 注:直接访问索引的键如果不存在就会报出异常
# 解决方法:使用get(key,default_value),如果key不存在会返回默认值default_value
d.get('dd','demo')
# 输出:'demo'

# 集合访问 ,
s = {1,2,3}
s[0]
# 输出:TypeError: 'set' object is not subscriptable
# 注:集合的访问不支持直接索引访问,因为其内部是一个hash表

# 判断key内容是否在字典内
d = {'name':'liuyi','age':18,'gender':'male'}
'name'in d
# 输出:True
'demo' d
# 输出:False

# 判断内容是否在集合内 
s = {1,2,3}
1 in s
# 输出:True
11 in s
# 输出:False

# 增删改
# 字典增删改
d = {'name':'liuyi','age':18,'gender':'male'}
d['heigh'] = 168 # 增加元素
d['age'] = 20 # 修改元素
d.pop('gender') # 删除key 为 gender的元素 
# 输出:{'name': 'liuyi', 'age': 20, 'heigh': 168}

# 集合赠删
s = {1,2,3}
s.add(4) # 增加元素
s.remove(1) # 删除元素

# 排序
# 字典排序
d = {'a': 20,'c': 18,'b': 2}
sorted(d.items(),key=lambda x: x[0]) # 按照key进行升序排序
# 输出:[('a', 20), ('b', 2), ('c', 18)]
sorted(d.items(),key=lambda x: x[1]) # 按照值进行升序排序
# 输出:[('b', 2), ('c', 18), ('a', 20)]

# 集合排序
s = { 2, 4, 1, 3 }
sorted(s) # 对集合内的元素进行升序排序
[1, 2, 3, 4]


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

二、性能

    相比于列表和元组,字典的性能更优,特别是对于查找、添加和删除操作,字典都能在常数时间复杂度内完成

    1. 为什么?

        因为字典和集合内部的存储结构都是hash表。

            - 字典:字典的内部是存储了哈希值、键和值这三个元素

            - 集合:与字典的区别就是哈希表内没有键和值的配对,只有单一的值

    2. 代码比较

# 遍历5万个商品查找商品总共有多少个价格,查看两个数据结构的性能情况
import time

# 使用数组
def find_unique_price_list(products):
    unique_price = []
    for id,price in products:
        if price not in unique_price:
            unique_price.append(price)
    return len(unique_price)

# 使用集合
def find_unique_price_set(products):
    unique_price = set()
    for id,price in products:
        if price not in unique_price:
            unique_price.add(price)
    return len(unique_price)

id = [x for x in range(0,50000)]
count = [x for x in range(50000,100000)]
products = list(zip(id,count))

# 数组完成时间
start_list_time = time.perf_counter()
find_unique_price_list(products)
end_list_time = time.perf_counter()
print("总共用时:{}".format(end_list_time-start_list_time))
# 输出:总共用时:15.7466

# 集合完成时间
start_set_time = time.perf_counter()
find_unique_price_set(products)
end_set_time = time.perf_counter()
print("总共用时:{}".format(end_set_time-start_set_time))
# 输出:总共用时:0.0063
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

注:由上可以看出仅仅5万的数据量,两者的速度差异就如此之大。如果再更大的数据量中如果使用了不适当的数据结构,很容易造成服务器崩溃和用户体验差等情况!!

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号