zoukankan      html  css  js  c++  java
  • python--集合

    set集合的去重机制 : 先调用hash,再调用eq,eq不是每次都触发,只有hash值相等的时候才会触发

    dic1 = set()  # 空集合
    dic = {"葫芦娃", "变形金刚"}
    print(type(dic))

    结果:

    <class 'set'>

    集合的常用操作

    list1 = set([1, 4, 5, 7, 3, 6, 7, 9])  # 将列表转为集合
    list2 = set([2, 6, 0, 66, 22, 8, 4])
    list3 = set([1, 3, 7])
    print(set(list1), set(list2))  # 转换成集合,去掉重复的值,保留唯一值
    print(list1.intersection(list2))  # 取两个集合的交集
    print(list1.union(list2))  # 并集,两个集合合并,去掉 重复的,保留唯一值
    print(list1.difference(list2))  # 差集list1里有list2里没有的
    print(list1.issubset(list2))  # 子集,输出True或False
    print(list1.issuperset(list3))  # 父集,list3里的都在list1里
    print(list1.symmetric_difference(list2))  # 对称差集,去掉重复的,放到一个集合里
    print(list1.isdisjoint(list2))  # 没交集返回为True,有交集返回False

    结果:

    {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 22, 8}
    {4, 6}
    {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
    {1, 3, 5, 7, 9}
    False
    True
    {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
    False
    list1 = set([1, 4, 5, 7, 3, 6, 7, 9])
    list2 = set([2, 6, 0, 66, 22, 8, 4])
    list3 = set([1, 3, 7])
    print(set(list1), set(list2))  # 转换成集合,去掉重复的值,保留唯一值
    print(list1 & list2)  # 交集
    print(list1 | list2)  # 并集 unio
    print(list1 - list2)  # 差集 differenc,跟位置有关系
    print(list1 ^ list2)  # 对称差集

    结果:

    {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 22, 8}
    {4, 6}
    {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
    {1, 3, 5, 7, 9}
    {0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
    list1 = set([1, 4, 5, 7, 3, 6, 7, 9])
    list2 = set([2, 6, 0, 66, 22, 8, 4])
    list3 = set([1, 3, 7])
    print(set(list1), set(list2))  # 转换成集合,去掉重复的值,保留唯一值
    list1.add(777)  # 添加一项
    print(list1)
    list1.update([555, 666, 888])  # 添加多项
    print(list1)
    list1.remove(555)  # 删除555
    print(list1)

    结果:

    {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 22, 8}
    {1, 3, 4, 5, 6, 7, 9, 777}
    {1, 3, 4, 5, 6, 7, 9, 777, 555, 888, 666}
    {1, 3, 4, 5, 6, 7, 9, 777, 888, 666}
  • 相关阅读:
    Web前端学习第三天·fighting_常用的一些标签(一)
    Web前端学习第七天·fighting_CSS样式的编写和使用(二)
    Web前端学习第八天·fighting_使用CSS美化文字(一)
    WPF 自定义RadioButton样式
    WPF自定义控件与样式自定义按钮(Button)
    WPF 自定义Calendar样式(日历样式,周六周日红色显示)
    WPF 自定义TextBox带水印控件,可设置圆角
    WPF 自定义CheckBox样式
    常见web UI 元素操作 及API使用
    selenium定位下拉框
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/12994798.html
Copyright © 2011-2022 走看看