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

Python修炼之路-数据类型

时间:2017-11-13 21:21:36      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:切片   有一个   slow   shell   ons   bst   返回   计算   创建   

Python编程之列表

列表是一个使用一对中括号"[   ]" 括起来的有序的集合,可以通过索引访问列表元素,也可以增加和删除元素。

列表的索引:第一个元素索引为0,最后一个元素索引为-1。

1 #列表的定义与访问
2 >>> L = [python, 11, True]
3 >>> print(L)     #[‘python‘, 11, True]
4 >>> L[-1]        # True
5 >>> L[0]         # ‘python‘
6 >>> L[2]         # True

Python常用方法:


 

技术分享

 

技术分享
 1 #***************插入*******************
 2 >>> L = [python, 11, True]
 3 >>> L.append(hello)                            #append插入
 4 >>> L
 5 #       [‘python‘, 11, True, ‘hello‘]
 6 >>> L.insert(0,False)                      #指定位置插入
 7 >>> L
 8 #[False, ‘python‘, 11, True, ‘hello‘]
 9 >>> L.insert(10,world)                  #插入索引区别
10 >>> L
11 #[False, ‘python‘, 11, True, ‘hello‘, ‘world‘]
12 >>> L[5]
13 #‘world‘
14 
15 #***************删除*******************
16 >>> L = [python, 11, True]  
17 >>> L.pop()     #True                      #pop弹出,默认弹出最后一个
18 >>> L              #[‘python‘, 11]
19 >>> L.pop(0)   #‘python‘                 #pop指定位置弹出
20 >>> L            #[11]
21 >>> L = [python, 11, True]
22 >>> L.remove(11)                           #remove删除
23 >>> L               #[‘python‘, True]
24 >>> L = ["A","B","C","D","E"]
25 >>> del L[2]                                  #删除一个元素 
26 >>> L               #[‘A‘, ‘B‘, ‘D‘, ‘E‘]
27 >>> del L[2:]                                #删除一个范围内的元素
28 >>> L              #[‘A‘, ‘B‘]
29 #***************更新*******************
30 >>> L = [python, 11, True]
31 >>> L[2] = False
32 >>> L                 #[‘python‘, 11, False]
33 #***************排序与索引*****************
34 >>> L.sort(reverse=True)     #排序
35 >>> L     #[‘E‘, ‘D‘, ‘C‘, ‘B‘, ‘A‘]
36 >>> L = ["A",1,"Bob"]       #注意不能和数字在一起排序
37 >>> L.sort()
38 Traceback (most recent call last):
39   File "<pyshell#34>", line 1, in <module>
40     L.sort()
41 TypeError: unorderable types: int() < str()
42 >>> L = ["A","1","Bob"]       #转换成字符串即可
43 >>> L.sort()
44 >>> L                    #[‘1‘, ‘A‘, ‘Bob‘]
45 >>> L.reverse()    #参考上面reverse=False
46 >>> L    #[‘Bob‘, ‘A‘, ‘1‘]
47 #***************扩展**********************
48 >>> M = ["1",2,"C"]
49 >>> L.extend(M)
50 >>> L                #[‘Bob‘, ‘A‘, ‘1‘, ‘1‘, 2, ‘C‘]
51 #***************其他用法*******************
52 >>> L = ["A","B","C","D","E"]        
53 >>> L.index("B")                #1    返回索引值
54 >>> L.count(C)                 #1    统计"value"出现的次数
View Code

 

列表切片:用于从列表或元组中截取元素。

截取原则:自左向右截取,顾头不顾尾原则。

 

usage: if the first index is ‘0’ or the last one, which could be ignored; Meanwhile slice could appoint the third parameter that means intercept one element out of every N element.

L[1:3]: it means that the index is from one to  three, but it doesn’t include this element which index is three

 1 >>> L = [A,1,True,a]
 2 >>> L[1:3]              #[1, True]
 3 >>> L = [A,1,True,’a’]
 4 >>> L[:2]               #[‘A‘, 1]
 5 >>> L[:]                 #[‘A‘, 1, True, ‘a‘]
 6 >>> L = range(1,10)
 7 >>> L[2::3]            #[3, 6, 9]
 8 >>> L[2:7:3]          #[3, 6]
 9 >>> L = range(1,11)
10 >>> L
11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12 >>> L[-5:-1]
13 [6, 7, 8, 9]
14 >>> L[-5:]
15 [6, 7, 8, 9, 10]
16 >>> L[-5::3]
17 [6, 9]

字符串切片处理

1 >>> asdfghjkl[:3]
2 asd
3 >>> asdfghjkl[-3:]
4 jkl
5 >>> asdfghjkl[::2]
6 adgjl

 

Python编程之元组

元组(tuple):一个用括号"()"括起来的有序序列,但是一旦创建便不可修改,所以又叫只读序列。

元组只有两个方法:count与index,参考list。

 1 # if there is one element in tuple, there should be add one ‘,’ after element.
 2 >>> t = (python,11,True)
 3 >>> t[0]
 4 python
 5 >>> t = (1)        #这只是一个数字,不是元组
 6 >>> t
 7 1
 8 >>> t = (1,)
 9 >>> t
10 (1,)

 

一个特殊的元组

1 >>> t = (a,b,[A,B])
2 >>> t
3 (a, b, [A, B])
4 >>> L = t[2]
5 >>> L[0] = X
6 >>> L[1] = Y‘
7 >>> t
8 (a, b, [X, Y])

技术分享

The unchangeable means tuple appointed should not be changed. Example, if appointed to a, it shouldn’t change to b.      

#关于更多的赋值与指向,可以参考深浅拷贝。

 

Python编程之字符串操作

字符串定义:用单引号或双引号括起来任意字符

特性:不可修改

转义字符:\

     \n : Enter       \t: tab    \\: \   \‘: ‘

raw string: 可以不使用"\"来转义。

1 print(r\(~_~)/(~_~)/)
2 #\(~_~)/(~_~)/

 

使用:"""..."""或者‘‘‘...‘‘‘表示多行字符串。

1 print(‘‘‘"To be, or not to be\": that is the question.
2 Whether it\‘s nobler in the mind to suffer.‘‘‘)         

字符串常用方法

 S.lower()                                                 小写 
 S.upper()  大写 
 S.swapcase()  大小写互换 
 S.capitalize()  首字母大写  
 S.title()   只有首字母大写,其余为小写
 S.ljust(width,"fillchar")  输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格
 S.rjust(width,"fillchar") 右对齐 
 S.center(width, "fillchar")  中间对齐 
 S.zfill(width) 把S变成width长,并在右对齐,不足部分用0补足,左边补0
 S.find(substr, [start, [end]])  返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索
 S.index(substr, [start, [end]])  与find()相同,只是在S中没有substr时,会返回一个运行时错误 
 S.rfind(substr, [start, [end]])  返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号 
 S.rindex(substr, [start, [end]])  计算substr在S中出现的次数 
 S.replace(oldstr, newstr, [count])  把S中的oldstar替换为newstr,count为替换次数。这是替换的通用形式,还有一些函数进行特殊字符的替换 
 S.strip([chars]) 把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None 
 S.rstrip([chars])   
 S.lstrip([chars])    
 S.expandtabs([tabsize])  把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个 
 S.split([sep, [maxsplit]])  以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符 
 S.rsplit([sep, [maxsplit]])   
 S.splitlines([keepends])  把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。 
 S.join(seq)  把seq代表的序列(字符串序列),用S连接起来
 S.encode([encoding,[errors]]) 
编码
 S.decode([encoding,[errors]])  译码
 S.startwith(prefix[,start[,end]])  是否以prefix开头 
 S.endwith(suffix[,start[,end]])  以suffix结尾 
 S.isalnum()  是否全是字母和数字,并至少有一个字符 
 S.isalpha() 是否全是字母,并至少有一个字符 
 S.isdigit()  是否全是数字,并至少有一个字符 ,如果是全数字返回True,否则返回False.
 S.isspace() 是否全是空白字符,并至少有一个字符 
 S.islower() S中的字母是否全是小写 
 S.isupper()  S中的字母是否便是大写 
 S.istitle()  S是否是首字母大写的
 trantab = str.maketrans(intab, outtab) 制表
 S.translate(trantab) 翻译,和上面的结合使用 

 

技术分享
  1 #-*-coding:utf-8 -*-
  2 
  3 
  4 poem = "gently I go as quietly as I came here"
  5 
  6 print(poem.capitalize())                  #首字母大写
  7 # Gently i go as quietly as i came here
  8 print(poem.lower())         #所有字母变成小写
  9 #  gently i go as quietly as i came here
 10 print(poem.upper())
 11 #GENTLY I GO AS QUIETLY AS I CAME HERE
 12 print(poem.swapcase())
 13 # GENTLY i GO AS QUIETLY AS i CAME HERE
 14 print(poem.casefold())                      #大写全部变小写
 15 #gently i go as quietly as i came here
 16 
 17 print(poem.center(80,"-"))      #输出80个字符,不足80个以“-”在字符串前后补充,字符串居中
 18 #---------------------gently I go as quietly as I came here----------------------
 19 print(poem.ljust(80,"*"))           #打印80个字符,字符串在前,不足80的部分用"*"补充
 20 #  gently I go as quietly as I came here*******************************************
 21 print(poem.rjust(80,"-"))
 22 #-------------------------------------------gently I go as quietly as I came here
 23 print(poem.zfill(80))                   #把字符串变成80个字符宽度,不足80的用0补足
 24 #0000000000000000000000000000000000000000000gently I go as quietly as I came here
 25 
 26 print(poem.count("e"))     #统计 e 出现次数
 27 # 5
 28 print(poem.find("e"))              #返回字符串中第一次出现“e”的标号,如果没有则返回-1;
 29 # 1                                  也可以poem.find("e",[start, [end]])设置返回,相当于poem[start:end]
 30 print(poem.rfind("e"))         #返回poem中最后一次出现"e"的标号,如果没有则返回-1,
 31 #36
 32 print(poem.rindex("e"))            #同rfind()
 33 #36
 34 print(poem.replace("e","E",2))     #replace(oldstr, newstr, [count]) , 替换
 35 #gEntly I go as quiEtly as I came here
 36 print("\n\tPython\t  is\n".strip())        #把前后的空格,换行制表等字符去掉
 37 print("\n\tPython\t  is\n".lstrip())
 38 print("\n\tPython\t  is\n".rstrip())
 39 print("\n\tPython\t  is".rstrip("s"))        #也可以指定字符去掉
 40 ‘‘‘
 41 Python      is
 42 Python      is
 43 
 44 
 45     Python      is
 46 
 47     Python      i
 48 ‘‘‘
 49 print(poem.encode())      #将字符串编码成bytes格式,解码为poem1.decode()
 50 # b‘gently I go as quietly as I came here‘
 51 
 52 print(poem.endswith("re"))  #判断字符串是否以 re结尾
 53 # True
 54 
 55 print("Python is a programming \tlanguage".expandtabs(10))   #将\t转换成10个空格,默认是8个
 56 # Python is a programming       language
 57 print(poem.find(e))    #查找e,返回第一次找到‘e‘的索引;如果找不到,返回-1
 58 # 1
 59 
 60 #------------------------format格式化输出--------------------------
 61 msg = "{} is a programming language, using {}"
 62 print(msg.format("Python",3))
 63 # Python is a programming language, using 3
 64 
 65 msg = "{1} is a programming language, using {0}"
 66 print(msg.format("Python",3))
 67 # 3 is a programming language, using Python
 68 
 69 msg = "{name} is a programming language, using {version}"
 70 print(msg.format(version=3,name="Python"))
 71 #Python is a programming language, using 3
 72 print(msg.format_map({ name:Python,version:3}))
 73 #Python is a programming language, using 3
 74 
 75 print(poem.index(h))    #返回字符串中第一个字符‘h‘的索引,如果没有会出现错误
 76 # 33
 77 
 78 print(90Ads.isalnum())     #字符串是否只包含字母或者数字,其他字符会返回False
 79 #True                  
 80 
 81 print(9.isdigit())      #字符串是否是只包含数字,如果包括其他字符,小数点,字母则返回False
 82 #True                   
 83 
 84 print(111.isnumeric())     #字符串是否只包含数字或者字符串数字
 85 # True
 86 
 87 print(poem.isprintable())     #是否可打印
 88 
 89 print( .isspace())          #是否为空格,含有其他字符返回False
 90 
 91 print(poem.istitle())         #是否为title,即每个单词的首字母是否为大写
 92 
 93 print(AA133..isupper())        #字符串中字母是否全部为大写,可以包括数字,其他字符等,不能包括小写字母
 94 #True
 95 
 96 
 97 print(poem.split())        #把poem分割成一个list,也可以指定分割符合分割次数,如下,默认分割符为空白符
 98 #[‘gently‘, ‘I‘, ‘go‘, ‘as‘, ‘quietly‘, ‘as‘, ‘I‘, ‘came‘, ‘here‘]
 99 print(poem.rsplit(" ",2))    #自右向左分割
100 # [‘gently I go as quietly as I‘, ‘came‘, ‘here‘]
101 print("""111111111111
102 222222222222
103 3333333333""".splitlines(True))         #按照行分割符分割成一个list,如果为真,每行后会保留分割符
104 #[‘111111111111\n‘, ‘222222222222\n‘, ‘3333333333‘]
105 print("-".join(["python","is","a"])) #把["python","is","a"]序列,一个字符一个字符的用“-”串起来
106 #python-is-a
107 
108 intab = "aeiou"  #This is the string having actual characters.
109 outtab = "12345" #This is the string having corresponding mapping character
110 trantab = str.maketrans(intab, outtab)
111 print(poem.translate(trantab))
112 #g2ntly I g4 1s q532tly 1s I c1m2 h2r2
113 
114 print("as d".isidentifier()) #检测一段字符串可否被当作标志符,即是否符合变量命名规则
115 #False
116 print(poem.partition("e"))    #如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,
117                                # 第二个为分隔符本身,第三个为分隔符右边的子串。
118 #(‘g‘, ‘e‘, ‘ntly I go as quietly as I came here‘)
String operation

 

Python编程之字典

访问元素更快,但是需要更多内存,通过key来访问value,所以key是唯一的;

key-value是无序的,区别list;

key是不可变的,数字,字符串,元组都可以作为key,list除外。

可以通过if判断key是否在字典中: if key in dict:

字典的查找、修改、增加、删除等用法

 1 #-*-coding:utf-8 -*-
 2 
 3 
 4 info = {
 5     "stu1" : "Jack",
 6     "stu2" : "Bob",
 7     "stu3" : "Adam"
 8 }
 9 print(info)
10 # {‘stu1‘: ‘Jack‘, ‘stu2‘: ‘Bob‘, ‘stu3‘: ‘Adam‘}     #无序的,每次打印顺序会变动
11 
12 #****************查找 ****************************
13 print(info["stu1"])         #不建议使用这种方式查找,如果所查元素不存在,会出错,Key error
14 print(info.get("stu1"))     #查找,如果不存在返回None,安全获取
15 print("stu2" in info)       #如果存在则返回True,判断是否存在;相当于python2.x中的info.has_key(‘stu2‘)
16 #True
17 
18 #****************修改 *************************
19 info["stu3"] = "Mary"    #如果存在,则是修改
20 print(info)
21 #{‘stu2‘: ‘Bob‘, ‘stu1‘: ‘Jack‘, ‘stu3‘: ‘Mary‘}
22 
23 #***************创建 *************************
24 info["stu4"] = "Kerry"    #如果不存在,则是创建
25 print(info)
26 #{‘stu2‘: ‘Bob‘, ‘stu1‘: ‘Jack‘, ‘stu3‘: ‘Mary‘, ‘stu4‘: ‘Kerry‘}
27 
28 #**************删除 **************************
29 del info["stu1"]                        # 删除 del
30 print(info)
31 #{‘stu2‘: ‘Bob‘, ‘stu3‘: ‘Mary‘, ‘stu4‘: ‘Kerry‘}
32 info.pop("stu2")                        #删除 pop(), 建议使用
33 print(info)
34 #{‘stu3‘: ‘Mary‘, ‘stu4‘: ‘Kerry‘}
35 info.popitem()                           #删除 popitem(), 随机删除,不建议使用
36 print(info)
37 #{‘stu3‘: ‘Mary‘}

 

多级字典嵌套及操作

 1 #***************多级字典嵌套******************
 2 Earth = {
 3            "Asia":{
 4                     "China" : ["Beijign","Shanghai"],
 5                     "Japan" : ["Tokyo","Osaka"]
 6             },
 7            "Europe":{
 8                     "France" : ["Paris","Lyons"],
 9                     "England":"London"
10             },
11             "North America":{
12                     "America":["Washington","New York"],
13                     "Canada" :"Ottawa"
14             }
15            }
16 print(Earth["Asia"]["China"])
17 #[‘Beijign‘, ‘Shanghai‘]
18 Earth["Asia"]["India"] = "New Delhi"
19 print(Earth["Asia"])
20 #{‘China‘: [‘Beijign‘, ‘Shanghai‘], ‘India‘: ‘New Delhi‘, ‘Japan‘: [‘Tokyo‘, ‘Osaka‘]}

 

字典的其他用法

技术分享
 1 #******************* 字典其他用法***************************
 2 info = {
 3     "stu1" : "Jack",
 4     "stu2" : "Bob",
 5     "stu3" : "Adam"
 6 }
 7 b = {
 8        "stu8" : "A",
 9        "stu1" : "B"
10 }
11 #******************* values()  *******************
12 print(list(info.values()))    #以列表返回字典中的所有值
13 #[‘Adam‘, ‘Jack‘, ‘Bob‘]
14 
15 #******************* values()  *******************
16 print(list(info.keys()))    #以列表返回字典中的key
17 #[‘stu1‘, ‘stu3‘, ‘stu2‘]
18 
19 #******************* setdefault()  *******************
20 info.setdefault("stu4","Mary")      #如果键不存在于字典中,将会添加键并将值设为默认值
21 print(info)
22 #{‘stu3‘: ‘Adam‘, ‘stu2‘: ‘Bob‘, ‘stu4‘: ‘Mary‘, ‘stu1‘: ‘Jack‘}
23 info.setdefault("stu1","Kelly")     #如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值
24 print(info.setdefault("stu1","Kelly") )
25 #Jack
26 print(info)
27 {stu3: Adam, stu2: Bob, stu4: Mary, stu1: Jack}
28 
29 #******************* update() *************************
30 info.update(b)                 #把字典b中的信息更新到字典info中,区别setdefault
31 print(info)                    #相当于合并字典,info有的元素就更新,没有的元素就添加
32 #{‘stu3‘: ‘Adam‘, ‘stu8‘: ‘A‘, ‘stu2‘: ‘Bob‘, ‘stu1‘: ‘B‘}
33 
34 #******************* items() *************************   以列表返回可遍历的(键, 值) 元组数组
35 print(info.items())               #将字典转化为列表,可用list()序列化
36 #dict_items([(‘stu8‘, ‘A‘), (‘stu1‘, ‘B‘), (‘stu2‘, ‘Bob‘), (‘stu3‘, ‘Adam‘)])
37 
38 #******************* fromkeys() *************************
39 c = dict.fromkeys([6,7,8],[1,{"name":"Jack"},123])        #创建一个新的字典,(键:值)
40 print(c)
41 #{8: [1, {‘name‘: ‘Jack‘}, 123], 6: [1, {‘name‘: ‘Jack‘}, 123], 7: [1, {‘name‘: ‘Jack‘}, 123]}
42 c[7][1]["name"] = "Bob"            #注意内存中数据的变化,参考深浅copy
43 print(c)
44 #{8: [1, {‘name‘: ‘Bob‘}, 123], 6: [1, {‘name‘: ‘Bob‘}, 123], 7: [1, {‘name‘: ‘Bob‘}, 123]}
dict用法

 

字典的循环

 1 #***************************字典的循环***********************************
 2 info = {
 3     "stu1" : "Jack",
 4     "stu2" : "Bob",
 5     "stu3" : "Adam"
 6 }
 7 for i in info:                #比下面循环高效,通过键值来查找
 8     print(i,info[i])
 9 # stu3 Adam
10 # stu1 Jack
11 # stu2 Bob
12 for k,v in info.items():
13     print(k,v)

 

 

 

 

 

 

技术分享

技术分享

技术分享

技术分享

Python修炼之路-数据类型

标签:切片   有一个   slow   shell   ons   bst   返回   计算   创建   

原文地址:http://www.cnblogs.com/gareth-yu/p/7780993.html

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