码迷,mamicode.com
首页 > 编程语言 > 详细

python开发【三】---集合

时间:2019-05-16 13:57:36      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:on()   lov   name   sub   print   %s   mat   不可   amp   

可变不可变:

可变:列表

不可变:字符串,数字,元组

访问顺序:

1.直接访问:数字

2.顺序访问:字符串,列表,元组

3.映射:字典

存放元素个数:

容器类型:列表,元组,字典

原子:数字,字符串

=================================

集合:set

定义:由不同的元素组成的集合,集合是一种无序排列的可hash值,可以作为字典的key(只可存放不可变类型,即只能存放字符串,数字,元组)

定义集合:例:s = {1,2,3,4,5,6}

例:add() 添加
    s = {1,2,3,4,5,6}
    s.add("3")
    print(s)
    结果:{1, 2, 3, 4, 5, 6, ‘3‘}
例:clear()清空
例:copy()拷贝
例: pop()删除,随机删除
例: remov(),删除指定元素,元素不存在会报错
例:discard(),删除指定元素,元素不存在不会报错 

集合的关系

例:intersection(),交集   ==&
    ps = ["aa","bb","cc","dd"]
    ls = ["bb","cc","ee","ff"]
    p_s = set(ps)
    l_s = set(ls)
    print(p_s.intersection(l_s))   === print(p_s&l_s)
    结果:{‘bb‘, ‘cc‘}
例:union(),并集       ==|
    ps = ["aa","bb","cc","dd"]
    ls = ["bb","cc","ee","ff"]
    p_s = set(ps)
    l_s = set(ls) 
    print(p_s.union(l_s))          ===print(p_s|l_s)
    结果:{‘aa‘, ‘bb‘, ‘ee‘, ‘cc‘, ‘ff‘, ‘dd‘}
例:difference(),差集     ==-
    ps = ["aa","bb","cc","dd"]
    ls = ["bb","cc","ee","ff"]
    p_s = set(ps)
    l_s = set(ls)
    print(p_s-l_s)
    结果:{‘aa‘, ‘dd‘}
例:symmetric_difference(),交叉补集   ==^
    ps = ["aa","bb","cc","dd"]
    ls = ["bb","cc","ee","ff"]
    p_s = set(ps)
    l_s = set(ls)
    print(p_s.symmetric_difference(l_s))
    结果:{‘dd‘, ‘ff‘, ‘aa‘, ‘ee‘}

 

例:difference_update(),差集以后更改原数据
    ps = ["aa","bb","cc","dd"]
    ls = ["bb","cc","ee","ff"]
    p_s = set(ps)
    l_s = set(ls)
    p_s.difference_update(l_s)
    print(p_s)
    结果:{‘aa‘, ‘dd‘}
例:isdisjoint(),比较2个集合是否有交集,有交集返回False
例:issubset(),包含关系,s1是s2的子集返回True
例:issuperset(),包含关系,s1是s2的父集返回True    ===  >=
 

  

字符串格式化---%或者format

1.format

1.%s传值(传任何值)

  例:传单个值

  print("i am %s my" %‘hhh‘)

   结果:i am hhh my

   例:传多个值

  print(‘i am %s i love %s‘ % ("dl","maod"))

   结果:i am dl i love maod

2.%d传数字

3.%f传递浮点数(小数)默认小数点后保留6位

例:

  tpl = "percent %f "% 8.8888

  print(tpl)

  结果:percent 8.888800

  tpl = "prcent %0.3f "% 8.8888        ==保留小数点后3位

  print(tpl)

  结果:prcent 8.889 

4.%%打印百分号

5.sep

print("root","x","0","2",sep=":")
结果:root:x:0:2

6.%字典的传递

tpl = "i am %(name)s and age is %(age)d" % {"name": "dl","age": 18}
print(tpl)
结果:i am dl and age is 18

 

 

 

---

python开发【三】---集合

标签:on()   lov   name   sub   print   %s   mat   不可   amp   

原文地址:https://www.cnblogs.com/liuchunling/p/10871030.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!