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

python/基本数据类型

时间:2017-04-24 17:18:31      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:text   post   center   代码   随机   more   指定元素   存在   cti   

基本数据类型(字符串_数字_列表_元祖_字典_集合)

1、字符串

技术分享

 

2、数字

  除了布尔类型外,int、long、float和complex都可以使用的运算为:加、减、乘、除、整除、幂运算和取余


3、列表和元组

列表的内容可变,可以包含任意对象,使用中括号表示。
元组的内容不可变,可以包含任意对象,使用圆括号表示。元组

1 l = [1, 2, 3, ‘4‘, ‘5‘] # 列表
2 l = list((1, 2, 3, ‘4‘, ‘5‘))
3 
4 t = (1, 2, 3, ‘4‘, ‘5‘) # 元组
5 t = tuple("1234")

技术分享

1 >>> l = [1, 2, 3, 4, 5]
2 >>> del l[1]
3 >>> l
4 [1, 3, 4, 5]

 

4、字典

字典(dict)是python为唯一的内置映射类型,任何不可变对象都可以用作字典的键值,如字符串、数字、元组等。字典使用大括号表示,键和值之间用冒号分割,各个键值间用逗号隔开。映射对象是无序的。

1 d = dict(([‘name‘, ‘wuyuan‘], [‘age‘, 23]))
2 d = {‘name‘: ‘wuyuan‘, ‘blog‘: ‘wuyuans.com‘, ‘age‘: 23}
3 d[‘school‘] = ‘HDU‘ # 添加一项

技术分享

字典的历遍方式

1 #使用键历遍
2 for i in d:
3     print i,d[i]
4 #使用键值历遍
5 for k,v in d.items():
6     print k,v

 

5、可变不可变:
1、可变:列表,字典
2、不可变: 字符串,数字,元组

 

6、访问顺序:
1、直接访问:数字
2、顺序访问:字符串,列表,元组
3、映射: 字典

 

7、存放元素个数:
容器类型:列表,元组,字典
原子:数字,字符串

 

详细参考:

技术分享

 


一、set集合(可变集合)  集合是一个无序而且不重复的集合,有些类似于数学中的集合,也可以求交集,求并集等

集合特性:
1、不同元素组成
2、无序
3、集合中元素必须是不可变类型

技术分享
  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5      
  6     Build an unordered collection of unique elements.
  7     """
  8     def add(self, *args, **kwargs): # real signature unknown
  9         """
 10         Add an element to a set,添加元素
 11          
 12         This has no effect if the element is already present.
 13         """
 14         pass
 15  
 16     def clear(self, *args, **kwargs): # real signature unknown
 17         """ Remove all elements from this set. 清除内容"""
 18         pass
 19  
 20     def copy(self, *args, **kwargs): # real signature unknown
 21         """ Return a shallow copy of a set. 浅拷贝  """
 22         pass
 23  
 24     def difference(self, *args, **kwargs): # real signature unknown
 25         """
 26         Return the difference of two or more sets as a new set. A中存在,B中不存在
 27          
 28         (i.e. all elements that are in this set but not the others.)
 29         """
 30         pass
 31  
 32     def difference_update(self, *args, **kwargs): # real signature unknown
 33         """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
 34         pass
 35  
 36     def discard(self, *args, **kwargs): # real signature unknown
 37         """
 38         Remove an element from a set if it is a member.
 39          
 40         If the element is not a member, do nothing. 移除指定元素,不存在不保错
 41         """
 42         pass
 43  
 44     def intersection(self, *args, **kwargs): # real signature unknown
 45         """
 46         Return the intersection of two sets as a new set. 交集
 47          
 48         (i.e. all elements that are in both sets.)
 49         """
 50         pass
 51  
 52     def intersection_update(self, *args, **kwargs): # real signature unknown
 53         """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
 54         pass
 55  
 56     def isdisjoint(self, *args, **kwargs): # real signature unknown
 57         """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
 58         pass
 59  
 60     def issubset(self, *args, **kwargs): # real signature unknown
 61         """ Report whether another set contains this set.  是否是子序列"""
 62         pass
 63  
 64     def issuperset(self, *args, **kwargs): # real signature unknown
 65         """ Report whether this set contains another set. 是否是父序列"""
 66         pass
 67  
 68     def pop(self, *args, **kwargs): # real signature unknown
 69         """
 70         Remove and return an arbitrary set element.
 71         Raises KeyError if the set is empty. 移除元素
 72         """
 73         pass
 74  
 75     def remove(self, *args, **kwargs): # real signature unknown
 76         """
 77         Remove an element from a set; it must be a member.
 78          
 79         If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
 80         """
 81         pass
 82  
 83     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 84         """
 85         Return the symmetric difference of two sets as a new set.  对称差集
 86          
 87         (i.e. all elements that are in exactly one of the sets.)
 88         """
 89         pass
 90  
 91     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
 92         """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
 93         pass
 94  
 95     def union(self, *args, **kwargs): # real signature unknown
 96         """
 97         Return the union of sets as a new set.  并集
 98          
 99         (i.e. all elements that are in either set.)
100         """
101         pass
102  
103     def update(self, *args, **kwargs): # real signature unknown
104         """ Update a set with the union of itself and others. 更新 """
105         pass
技术分享

 

技术分享

 


set用法练习

练习一:

1、set输出

1 s=set(‘hello‘)
2 print(s)

执行结果:

1 {‘l‘, ‘e‘, ‘h‘, ‘o‘}

 

2、set去重

ps1:

1 s=set([‘alex‘,‘alex‘,‘sb‘])
2 print(s)

执行结果:

1 {‘sb‘, ‘alex‘}

 

ps2:

1 names=[‘alex‘,‘alex‘,‘wupeiqi‘]
2 names=list(set(names))
3 print(names)

执行结果:

1 [‘alex‘, ‘wupeiqi‘]

 

3、add 添加元素 (只能更新一个值)

1 s = {1, 2, 3, 4, 5, 6}
2 s.add(‘s‘)
3 s.add(‘3‘)
4 s.add(3)
5 print(s)

执行结果:

1 {1, 2, 3, 4, 5, 6, ‘s‘, ‘3‘}

 

4、clear 清空元素

1 s = {1, 2, 3, 4, 5, 6}
2 s.clear()
3 print(s)

执行结果:

1 set()

 

5、copy 拷贝元素

1 s = {1, 2, 3, 4, 5, 6}
2 s1=s.copy()
3 print(s)

执行结果:

1 {1, 2, 3, 4, 5, 6}

 

6、pop随机删

1 s={‘sb‘,1,2,3,4,5,6}
2 s.pop()
3 print(s)

执行结果:

1 {2, 3, 4, 5, 6, ‘sb‘}

 

7、remove discard 指定删除  

remove 删除不存在元素,会报错。

discard  删除不存在元素,不会报错。

1 s={‘sb‘,1,2,3,4,5,6}
2 s.remove(‘sb‘)
3 s.remove(‘hellol‘)     ‘‘‘集合中不存在这个元素,删除不存在元素会报错‘‘‘
4 s.discard(‘sbbbb‘)     ‘‘‘集合中不存在这个元素,删除不存在元素不会报错‘‘‘
5 print(s)

执行结果:

1   File "D:/python/day5/集合.py", line 32
2     s.remove(‘hellol‘)     ‘‘‘删除元素不存在会报错‘‘‘
3                                           ^
4 SyntaxError: invalid syntax

 


二、集合的交集、并集、差集

 技术分享

 

集合支持一系列标准操作,包括并集、交集、差集和对称差集。

例如: 

技术分享
1 a = t | s          # t 和 s的并集  
2   
3 b = t & s          # t 和 s的交集  
4   
5 c = t – s          # 求差集(项在t中,但不在s中)  
6   
7 d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中) 
技术分享

 

用法示例:

 1、intersection 求交集(交集:两边都存在相同的内容,就取出来)

技术分享
1 python_l=[‘lcg‘,‘szw‘,‘zjw‘,‘lcg‘]
2 linux_l=[‘lcg‘,‘szw‘,‘sb‘]
3 p_s=set(python_l)
4 l_s=set(linux_l)
5 print(p_s,l_s)
6 
7 #求交集 (交集:两边都存在相同的内容,就取出来)
8 print(p_s.intersection(l_s))
9 print(p_s&l_s)
技术分享

执行结果:

1 {‘szw‘, ‘zjw‘, ‘lcg‘} {‘szw‘, ‘sb‘, ‘lcg‘}
2 {‘szw‘, ‘lcg‘}
3 {‘szw‘, ‘lcg‘}

 

 2、union 求并集(并集:两个集合的元素合到一起)

技术分享
1 python_l=[‘lcg‘,‘szw‘,‘zjw‘,‘lcg‘]
2 linux_l=[‘lcg‘,‘szw‘,‘sb‘]
3 p_s=set(python_l)
4 l_s=set(linux_l)
5 print(p_s,l_s)
6 print(p_s.union(l_s))
7 print(p_s|l_s)
技术分享

执行结果:

1 {‘lcg‘, ‘zjw‘, ‘szw‘} {‘lcg‘, ‘sb‘, ‘szw‘}
2 {‘lcg‘, ‘szw‘, ‘sb‘, ‘zjw‘}
3 {‘lcg‘, ‘szw‘, ‘sb‘, ‘zjw‘}

 

3、difference  差集 (差集:两个数相减,得出的结果就是差集)

ps1:

技术分享
 1 python_l=[‘lcg‘,‘szw‘,‘zjw‘,‘lcg‘]
 2 linux_l=[‘lcg‘,‘szw‘,‘sb‘]
 3 p_s=set(python_l)
 4 l_s=set(linux_l)
 5 print(p_s,l_s)
 6 
 7 print(‘差集‘,p_s-l_s)
 8 print(p_s.difference(l_s))  
 9 
10 print(‘差集‘,l_s-p_s)
11 print(l_s.difference(p_s))
技术分享

执行结果:

1 {‘zjw‘, ‘szw‘, ‘lcg‘} {‘sb‘, ‘szw‘, ‘lcg‘}
2 差集 {‘zjw‘}  #左边减右边,减去左边和右边相同的,得出左边不相同的
3 {‘zjw‘}
4 差集 {‘sb‘}   #右边减左边,减去右边和左边相同的,得出右边不相同的
5 {‘sb‘}

 

ps2: 差集 p_s-l_s  

1 python_l=[‘lcg‘,‘szw‘,‘zjw‘,‘lcg‘]
2 linux_l=[‘lcg‘,‘szw‘,‘sb‘]
3 p_s=set(python_l)
4 l_s=set(linux_l)
5 print(p_s,l_s)
6 print(‘差集‘,p_s-l_s)  #去掉同时报两门课程的人,得出只学一门课程的人

执行结果:

1 {‘lcg‘, ‘szw‘, ‘zjw‘} {‘lcg‘, ‘szw‘, ‘sb‘}
2 
3 差集 {‘zjw‘}  #结果得出只学一门课程的人

 

 4、symmetric_difference 交叉补集 (交叉补集:先把两个合在一起,然后去掉两个都有的共同部分)

 技术分享

技术分享
1 python_l=[‘lcg‘,‘szw‘,‘zjw‘,‘lcg‘]
2 linux_l=[‘lcg‘,‘szw‘,‘sb‘]
3 p_s=set(python_l)
4 l_s=set(linux_l)
5 print(p_s,l_s)
6 print(‘交叉补集‘,p_s.symmetric_difference(l_s))
7 print(‘交叉补集‘,p_s^l_s)
技术分享

执行结果:

1 {‘szw‘, ‘zjw‘, ‘lcg‘} {‘szw‘, ‘sb‘, ‘lcg‘}
2 交叉补集 {‘sb‘, ‘zjw‘}
3 交叉补集 {‘sb‘, ‘zjw‘}

 

5、差集 difference_update

技术分享
1 python_l=[‘lcg‘,‘szw‘,‘zjw‘,‘lcg‘]
2 linux_l=[‘lcg‘,‘szw‘,‘sb‘]
3 p_s=set(python_l)
4 l_s=set(linux_l)
5 print(p_s,l_s)
6 # print(‘差集‘,p_s-l_s)  #去掉同时报两门课程的人,得出只学一门课程的人
7 p_s=p_s-l_s
8 p_s=p_s-l_s  = p_s.difference_update(l_s)
9 print(p_s)
技术分享

 

6、isdisjoint 交集 (是否有交集,有的话返回False,没有的话返回True)

1 s1={1,2}
2 s2={3,5       #没有相同的就返回True
3 #s2={2,3,5}   #有相同的就返回False
4 print(s1.isdisjoint(s2))

执行结果:

1 True     #s2={3.5}
2 Flase    #s3={2,3,5}

 

7、issubset (s1<=s2)   s1是s2的子集 or s2是s1的父集 

     issuperset  (s1>=s2)  判断一个集合是另一个集合的子集  (s2 是s1 的父集)

技术分享

1 s1={1,2}
2 s2={1,2,3}
3 print(s1.issubset(s2))    #s1 是s2 的子集
4 print(s2.issubset(s1))    #False
5 print(s2.issuperset(s1))  #判断一个集合是另一个集合的子集 (s2 是s1的父集)

执行结果:

1 True
2 False
3 True

 

8、update 更新多个值

1 s1={1,2}
2 s2={1,2,3}
3 # s1.update(s2) #更新多个值

执行结果:

1 {1, 2, 3}

 

 

9、frozenset  不可变集合  元素一经创建,不可增加、删除和修改。因此没有add、pop、discard、remove和所有以_update结尾的方法。但可以作为左值接受赋值。

  frozenset和set混合运算时,返回的值以左边的操作变量为准。

ps1:

1 frozenset(a) | set(b)   的返回值就是frozenset,
2 
3 set(a) | frozenset(b)  的返回值就是set

 

ps2:

1 s1=frozenset(‘hello‘)
2 print(s1)

执行结果:

1 frozenset({‘l‘, ‘h‘, ‘o‘, ‘e‘})

 


其它练习

技术分享
 1 s1={1,2,3,1}                #定义一个set s1 如果s1={}为空则默认定义一个字典
 2 s2=set([2,5,6])             #定义一个set s2
 3 print(s1)                   #s1={1,2,3} 自动去除重复的元素
 4  
 5 s1.add(5)                   #s1={1,2,3,5} 添加一个元素
 6 print(s1)
 7  
 8 s3=s1.difference(s2)        #返回一个s1中存在而不存在于s2的字典s3,s3={1,3},而s1并没有改变
 9 print(s3)
10  
11 s1.difference_update(s2)    #s1跟新成上面的s3 s1={1,3}
12 s1.discard(1)               #删除元素1,不存在的话不报错  s1={3}
13 print(s1)
14 s1.remove(3)                #删除元素3,不存在的话报错    s1={}
15 print(s1)
16 s1.update([11,2,3])         #跟新s1中的元素,其实是添加   s1={11,2,3}
17 print(s1)
18 k=s1.pop()                  #删除一个元素,并将删除的元素返回给一个变量,无序的,所以并不知道删除谁
19  
20                   
21 s1={1,2,3,4}          #这里重新定义了集合s1,s2
22 s2={3,4,5,6}
23 r1=s1.intersection(s2)       #取交集,并将结果返回给一个新的集合 r1={3,4}
24 print(r1)
25 print(s1)
26 s1.intersection_update(s2)   #取交集,并将s1更新为取交集后的结果 s1={3,4}
27 print(s1)
28  
29 k1=s1.issubset(s2)           #s1是否是s2的的子序列是的话返回True,否则False 这里k1=true
30 print(k1)
31 k2=s1.issuperset(s2)         #s1是否是s2的父序列 k2=False
32  
33 k3=s2.isdisjoint(s1)         #s1,s2,是否有交集,有的话返回False,没有的话返回True
34 print(k3)
35 s1.update([1,2])             #s1={1,2,3,4}
36 r3=s1.union(s2)              #取并集将结果返回给r3 r3={1,2,3,4,5,6}
37 print(r3)
38 r2=s1.symmetric_difference(s2)          #r2=s1并s2-s1交s2  r2={1,2,5,6}
39 print(r2)
40 s1.symmetric_difference_update(s2)      #s1更新为 s1并s2 - s1交s2   s1={1,2,5,6}
41 print(s1)

python/基本数据类型

标签:text   post   center   代码   随机   more   指定元素   存在   cti   

原文地址:http://www.cnblogs.com/guobaoyuan/p/6757646.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!