Python开发【第三篇】:Python基本数据类型
运算符
1、算数运算:
2、比较运算:
3、赋值运算:
4、逻辑运算:
5、成员运算:
基本数据类型
1、数字
int(整型)
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
2、布尔值
真或假
1 或 0
3、字符串
字符串常用功能:
- 移除空白 strip
- 分割 split
- 长度 len
- 索引 index
- 切片 str[0:]
- t
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# num = 9 // 2 # print(num) # print("hello world") # name = "好利来" # "好利来" 字符串 # "好" 字符 # "好利来" "利来" 子字符串, 子序列 # if "好" in name: # print('OK') # else: # print('Error') # if "文" not in name: # print('1') # else: # print('2') # v = "文" not in name # print(v) # user = "alex" # pwd = "123" # v = user == 'alex' and pwd == "123" or 1 == 1 and pwd =="982" # print(v) # a = 123 # v = a.bit_length() #求出a的二进制位数 # print(v) #大写 # name1 = "huahuashijie" # v1 = name1.upper() # print(v1) # name2 = "laiying" # v2 = name2.upper() # print(v2) # 整形, int # python3 里, 123124141243124124 # python2 里, 123123 范围 # long int # 长整形 # =========python3 ========= # 整形 int # python3 里 # a = 123 所有的功能,都放在int里 # a.bit_length() # 字符串 str # s1= "alex" # s2 = "root" # s1.title() # s1.upper() # s1.startswith('xx') ####列表 list # list #####元祖 tuple #####字典 dict # 布尔值 bool # test = "aLex" # 首字母大写 # v = test.capitalize() # 字母小写 casefold 更牛,很多未知的对相应小写 # v = test.casefold() # v2 = test.lower() # 设置宽度,并将内容居中 # 20 代指总长度 # * 空白未知填充,一个字符 # v= test.center(20,"*") # test = "alex" # v = test.ljust(20,"*") # print(v) # test = "alex" # v = test.rjust(20,"*") # print(v) # test = "alex" # v = test.zfill(20) # print(v) ## 去字符串中寻找,寻找子序列的出现次数 # test = "alexalexr" # v = test.count('ex',5) # 以什么什么结尾 # 以什么什么开始 # test = "alex" # v = test.endswith('ex') # v = test.endswith('a') # 从开始往后找,找到第一个之后,获取其位置 # test = "alexalex" # v = test.find('ex',5,8) # 格式化,将一个字符串中的占位符替换为指定的值 # test = 'i am {name},age {a}' # print(test) # v = test.format(name='alex',a=19) # test = 'i am {0},age {1}' # print(test) # v = test.format('alex',19) # 格式化,传入的值({"name":'alex',"a":19}) # test = 'i am {name},age {a}' # v1 = test.format(name='df',a=10) # v2 = test.format_map({"name":'alex',"a":19}) ####index找不到,报错 # test = "alexalex" # v = test.index('8') ###字符串中是否只包含 字母和数字 # test = "uasf890" # v = test.isalnum() # expandtabs,断句20 # s = "ausfouwelsjfsf\t0129sfsfoiweusfj" # v = s.expandtabs(20) ####isalpha 是否是字母 # test = "asfsfd中" # v = test.isalpha() # 当前输入是否是数字 # test = ' 2⃣' # v1 = test.isdecimal() # v2 = test.isdigit() # v3 = test.isnumeric() # print(v1,v2) # 字母,数字,下划线:标识符 def class # a = "_#def_asdf123" # v = a.isidentifier() # 是否存在不可显示的字符 # \t 制表符 # \n 换行符 # test = "opsfk\tdskdfwe" # v = test.isprintable() # 判断是否全部是空格 # test = " " # v = test.isspace() # 判断是否是标题,首字母都大写 # test = "In a title-cased string, upper- and title-case characters may only" # v = test.title() # print(v) # v2 = v.istitle() # print(v2) #######将字符串中的每一个元素按照指定分隔符进行拼接 # test = "你是风儿我是沙" # print(test) # t = ' ' # v = "_".join(test) # 判断是否都是小写,和转化小写 # test = "Alex" # v1 = test.islower() # v2 = test.lower() # print(v1,v2) # v1 = test.isupper() # v2 = test.upper() # 去除左右空白,去除\t \n ,去除指定字符(只要有相关的都能去掉) # test= "xalex" # v = test.lstrip('xa') # v = test.rstrip() # v = test.strip() ##相互对照替换 # v = "qwerqwer" # test = "你是风儿我是沙" # test1 = "去你的风和沙" # m = str.maketrans("aeiou","12345") # new_v = v.translate(m) # test = "testasdfqwerasf" # v = test.partition('s') # v = test.rpartition('s') # v = test.split('s',2) # test.rstrip() # 分割,只能根据 true False 是否保留换行 # test = "asfsdf\nwersdfsf\nsafwqersafd\nasfasf" # v = test.splitlines(True) # 以什么开头 # test = "backend 1.1.1.1 " # v = test.startswith("a") # v = test.endswith("a") # 大小写转换 # test = "alex" # v = test.swapcase() ###替换 # test = "alexalexalex" # v = test.replace("ex",'bbb',2) # print(v) #########6个基本魔法 # join,split,find,strip,lower,upper,replace # "alex" # "uile" # print(v) ###############################灰魔法 # test = "哈文文" # 索引,下标,获取字符串中的某一个字符 # v = test[2] # print(v) # 切片 # v = test[0:-1] #0=< <1 ##len获取当前字符串中由几个字符组成 # v = len(test) # li = [11,22,33,4,55,"asdf"] # len("asdfsadfsf") # v = len(li) # test = "哈文水淀粉来吧" # index = 0 # while index < len(test): # v = test[index] # print(v) # index += 1 # print('===============') ##for 循环 # for 变量名 in 字符串: # print(变量名) # for zj in test: # print(zj) # 注意:别的数据类型也能用 # len # for # 索引 # 切片 # test = input(">>>>>") # print(test) # for item in test: # print(item) # break # 帮助创建连续的数字,通过设置步长来指定不连续 # v = range(0,100,5) # for item in v: # print(item) # for item in range(0,len(test)): # print(test[item],item) # name = "zhengjianwen" # age = "18" # info = name + age # print(info)
4、列表
创建列表:
1
2
3
|
name_list = [ 'alex' , 'seven' , 'eric' ] 或 name_list = list ([ 'alex' , 'seven' , 'eric' ]) |
基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 切片
- 循环
- 包含
-
# list # 类 # li = [1, 29, "age", ["是正文", "庞麦郎"], "alex", True] # 通过list类创建的对象,li # 列表格式 # 中括号扩起来 # ,分割每个元素 # 列表中的元素可以是数字,字符串,列表,布尔值。。所有的都能放进去 # "集合",内部放置任何东西 """ ###############################灰魔法:list类中提供的方法 print(li[0]) # 切片,切片结果也是列表 print(li[3:5]) print(li[3:-1]) # for 循环 #while 循环 for item in li: print(item) """ # 列表元素,可以被修改 # li = [1, 29, "age", ["是正文", "庞麦郎"], "alex", True] ############## 索引 # 修改 # li[1:3] = [120,90] # li[1] = 120 # li[1] = [11,22,33,44] # print(li) ################切片 # 删除 第一种方式 # del li[1] # del li[2:6] ############# # 8 in 操作 # v = 29 in li # print(v) ########列表中的元素, # 9 操作 # li = [1, 29, "age", ["是正文", "庞麦郎"], "alex", True] # print(li[3][0]) ######################深灰魔法################### # 字符串转换列表 li = list("asdfasf") 内部使用for循环 # s = "pouasdfkljwqerkjsaf" # new_li = list(s) # print(new_li) ##列表转化成字符串,需要for循环转化成字符串 ,相加 # 直接使用字符串join方法, 列表中只有字符串 # s = "" # li = [11,22,33,"123","alex"] # for i in li: # s = s + str(i) # print(s) li = [11, 55,22, 33, 44] # 参数 # 原来值最后追加 # li.append(5) # 清空列表 # li.clear() # 3.拷贝,浅拷贝 # v = li.copy() # 4.计算元素出现的次数 # v = li.count(22) # 5.扩展原来列表 # li.append([99888,"budeliao"]) # li.extend([99888,"budeliao"]) # li.extend("budeliao") # 6 根据值获取当前值索引位置(左边优先) # v = li.index(22) # 7 在指定索引位置插入 # li.insert(0,99) # 8 删除某个值(1,指定索引,默认最后一个),并获取删除的值 # v = li.pop(1) #li.remove(33) #PS: pop remove del li[0] del[0:9] clear #9, 将当前列表进行反转 #li.reverse() #10。排序 #li.sort() #li.sort(reverse=True) #print(li) # print(v) #cmp #key #列表是有序的,元素可以被修改
5、元祖
创建元祖:
1
2
3
|
ages = ( 11 , 22 , 33 , 44 , 55 ) 或 ages = tuple (( 11 , 22 , 33 , 44 , 55 )) |
基本操作:
- 索引 index
- 切片 tu[0]
- 循环 for
- 长度 len
- 包含
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#################元组 #tuple 元素不可被修改,不能被增加或者删除 #tu = (111,"asdf",(),[],333,55,) #一般写元组的时候,推荐再最后加一个逗号 #切片 #v = tu[0] #v = tu[0:2] #可以被for循环,可迭代对象 #for item in tu: # print(item) #print(v) # s = "asdfsfkj" # li = ["asdf",12323] # tu = (123,123,"asdfasf") # v = list(tu) #li = ["asf","234wer"] #li.extend((11,22,33,)) #tu = (111,"asdf",(),[(33,44)],333,55,) ####元组也是有序的 #tu[3][0][0] #6.元组的一级元素不可修改/删除/增加 #tu[0] = 123 #v = tu[3] #tu[3][0] = 567 #tu.count(111) #tu.index(333) #print(tu)
6、字典(无序)
创建字典:
1
2
3
|
person = { "name" : "mr.wu" , 'age' : 18 } 或 person = dict ({ "name" : "mr.wu" , 'age' : 18 }) |
常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对
- 循环
- 长度
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#dict # info = { # "k1" : "v1", #键值对 # "k2" : "v2" # } # 字典的value可以是任何值 info = { "k1" : 18, "k2" : True, "k3" : [ 11, 22, 33, { 'kk1' : 'vv1', 'kk2' : 'vv2', 'kk3' : (11,22), } ], "k4" : "asdf" } #列表不能作为字典的key,字典也不能作为字典的key,布尔值也不可以, # info = { # 1 : 'asdf', # "k1" : 'sdf32', # #[11,22] : "123", # (11,22) : 123 # } #4.字典无序 #v = info['k1'] #v = info['k3'][3]['kk3'][0] #del info['k1'] #del info['k3'][3]['kk3'] #for 循环 # for item in info.keys(): # print(item) #for item in info.values(): # print(item) # for k,v in info.items(): # print(k,v) #print(info) ################################### #字典 #dict dic = { "k1" : "v1" , "k2" : "v2" } #根据序列,创建字典,并指定统一的值 #v = dict.fromkeys(["k1",123,"999"],123) #print(v) ######根据key获取值,默认返回none #v = dic['k1'] #print(v) #v = dic.get('k1',11111) #print(v) #删除并获取值 #v = dic.pop('k1') #print(dic,v) #k,v = dic.popitem() #print(dic,k,v) #设置值,已存在,不设置,获取当前key对应的值 #不存在,设置,获取当前key对应的值 #v = dic.setdefault('k1','123') #print(dic,v) #更新 #dic.update({'k1' : 11111, 'k3' : 123}) #print(dic) #dic.update(k1=123,k3=24,k5="asdf") # **swags #print(dic) #keys() values() items() get update
7.集合
无序
不同元素组成
不可变元素
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# s=set('hello') # print(s) # # s= set(['alex','alex','sb']) # print(s) #集合的内置方法 #s={1,2,3,4,5,'sb'} ##add 方法 #s.add('s') #s.add('3') #清空 #s.clear() #复制 #s1=s.copy() #随机删除 #s.pop() #指定删除 #s.remove('sb') #s.remove('hellooooo') #删除不存在会报错 #s.discard('sbbbb') #删除不存在元素不报错 python_l = ['lcg','szw','zjw'] linux_l = ['lcg','szw','wyh'] #集合可以去重 p_s = set(python_l) l_s = set(linux_l) #求交集 # print(p_s,l_s) # print(p_s.intersection(l_s)) # print(p_s&l_s) #求并集 #print(p_s.union(l_s)) #print(p_s|l_s) #求差集 # print(p_s-l_s) # print('差集',l_s-p_s) # print(p_s.difference(l_s)) # paython_and_linux = [] # for p_name in python_l: # if p_name in linux_l: # paython_and_linux.append(p_name) # # print(paython_and_linux) #print(s) #求补集 # print(p_s.symmetric_difference(l_s)) # print('交叉补集',p_s^l_s) #求差集再做更新 #p_s=p_s-l_s #p_s.difference_update(l_s) #print(p_s) # s1 = {1,2} # s2 = {3,4} # print(s1.isdisjoint(s2)) # # print(s1.issubset(s2)) #s1 是s2的子集 # # print(s2.issuperset(s1)) #s1 是s2 的父集 #s = frozenset('hello') #print(s)
PS:循环,range,continue 和 break
其他
1、for循环
用户按照顺序循环可迭代对象中的内容,
PS:break、continue
1
2
3
|
li = [ 11 , 22 , 33 , 44 ] for item in li: print item |
2、enumrate
为可迭代的对象添加序号
1
2
3
|
li = [ 11 , 22 , 33 ] for k,v in enumerate (li, 1 ): print (k,v) |
3、range和xrange
指定范围,生成指定的数字
1
2
3
4
5
6
7
8
|
print range ( 1 , 10 ) # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9] print range ( 1 , 10 , 2 ) # 结果:[1, 3, 5, 7, 9] print range ( 30 , 0 , - 2 ) # 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2] |
练习题
一、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
#!/usr/bin/env python3 # -*- coding:utf-8 -*- dic = {'k1' : [],'k2':[]} li = [11,22,33,44,99,90,88,57] for i in li: if i < 66 : dic['k1'].append(i) else: dic['k2'].append(i) for i in dic.keys(): print(i,dic[i])
二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
#!/usr/bin/env python3 # -*- coding:utf-8 -*- li = ["alec", " aric", "Alex", "Tony", "rain"] tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"} for i in li/tu/dic.values(): i=i.strip() if i.startswith('a') and i.endswith('c'): print(i) else : pass
三、输出商品列表,用户输入序号,显示用户选中的商品
商品 li = ["手机", "电脑", '鼠标垫', '游艇']
#!/usr/bin/env python3 # -*- coding:utf-8 -*- li = ["手机", "电脑", '鼠标垫', '游艇'] for i,v in enumerate(li,1): print(i,v)
四、购物车
功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物车
1
2
3
4
5
6
|
goods = [ { "name" : "电脑" , "price" : 1999 }, { "name" : "鼠标" , "price" : 10 }, { "name" : "游艇" , "price" : 20 }, { "name" : "美女" , "price" : 998 }, ] |
五、用户交互,显示省市县三级联动的选择
1
2
3
4
5
6
7
8
9
10
11
12
13
|
dic = { "河北" : { "石家庄" : [ "鹿泉" , "藁城" , "元氏" ], "邯郸" : [ "永年" , "涉县" , "磁县" ], } "河南" : { ... } "山西" : { ... } } |