Python之旅Day2 元组 字符串 字典 集合
元组(tuple)
元组其实跟列表差不多,也是存一组数,与列表相比,元组一旦创建,便不能再修改,所以又叫只读列表。
语法:
- names = ("Wuchunwei","Yangmengmeng","Lvs")
- #元组只有2个方法,一个是count,一个是index
- >>> tuple1 = (,,'',,'')
- >>> print (tuple1[])
- >>> print (tuple1[-])
- >>> print (tuple1[:]) #元组也可以进行切片操作。对元组切片可以得到新的元组。
- (, '')
- >>>
枚举
- >>> for i,v in enumerate(range(,)):
- ... print(i,v)
- ...
- >>>
应用举例:
- #代码
- product_list = [
- ['IPhone',],
- ['ofo',],
- ['MackBook',],
- ]
- for index,i in enumerate(product_list):
- print("%s,\t%s\t%s" %(index,i[],i[]))
- #运行结果
- C:\Python35\python.exe D:/Python代码目录/day2/list.py
- , IPhone
- , ofo
- , MackBook
- Process finished with exit code
字符串操作(str)
特性:不可修改
常用操作:
- >>> name = 'chunwei wu'
- >>> name.capitalize() #首字母大写
- 'Chunwei wu'
- >>>
- >>> name = 'CHUNWEI WU'
- >>> name.casefold() #全部大写变小写
- 'chunwei wu'
- >>>
- >>> name
- 'CHUNWEI WU'
- >>> name.center(20,"-") #输出20个字符,不足的以"-"补全
- '-----CHUNWEI WU-----'
- >>>
- >>> name
- 'CHUNWEI WU'
- >>> name.count('U') #统计(默认是统计所有,可以指定统计范围)
- 2
- >>> name.count('U',0,10)
- 2
- >>> name.count('U',0,9)
- 1
- >>>
- >>> name
- 'CHUNWEI WU'
- >>> name.endswith("Wu") #以什么结尾,匹配到则为真(返回True),匹配不到则为假(返回False)
- False
- >>> name.endswith("WU")
- True
- >>> name.endswith("CHUNWEI")
- False
- >>>
- >>> "Chunwei\tWu".expandtabs(10) #将\t转换成多长的空格
- 'Chunwei Wu'
- >>> "Chunwei\tWu".expandtabs(15)
- 'Chunwei Wu'
- >>> name
- 'CHUNWEI WU'
- >>> name.find('Wu') #查找Wu,找到返回其索引,找不到返回-1
- -1
- >>> name.find('CHUNWEI')
- 0
- #format格式的三种赋值方式
- >>> msg = "my name is {},and age is {}"
- >>> msg.format("chunweiwu",23)
- 'my name is chunweiwu,and age is 23'
- >>>
- >>> msg = "my name is {0},and age is {1}"
- >>> msg.format("chunweiwu",23)
- 'my name is chunweiwu,and age is 23'
- >>>
- >>> msg = "my name is {name},and age is {age}"
- >>> msg.format(age=23,name="chunweiwu") #无需位置对齐
- 'my name is chunweiwu,and age is 23'
- >>>
- #format_map格式赋值
- >> > msg = "my name is {name}, and age is {age}"
- >> > msg.format_map({'name': 'chunweiwu', 'age': 23})
- 'my name is chunweiwu, and age is 23'
- >>> "abCDe".isalpha() #是不是字母,是则为True,不是则为False
- True
- >>> "123e".isalpha()
- False
- >>>
- >>> "".isdigit() #是不是正整数,是返回True,否返回False
- True
- >>> "".isdigit()
- True
- >>> "-5".isdigit()
- False
- >>>
- >>> "al_ex".isidentifier() #是不是一个合法的变量名,是返回True,否返回False
- True
- >>> "2x".isidentifier()
- False
- >>>
- >>> "wei".islower() #是不是小写(全部)
- True
- >>> "weiG".islower()
- False
- >>>
- >>> "3.1".isnumeric() #是不是数字(不带小数点),是为True,否为False
- False
- >>> "".isnumeric()
- True
- >>> "31.45".isnumeric()
- False
- >>>
- >>> "weiG".isupper() #是不是大写(全部)
- False
- >>> "WeiG".isupper()
- False
- >>> "WG".isupper()
- True
- >>>
- >>> print("My Name Is Wu".istitle()) #是不是首字母都是大写
- True
- >>> print("My Name Is su".istitle())
- False
- >>>
- >>> ",".join("hello") #以指定的字符连接字符
- 'h,e,l,l,o'
- >>> "-".join("wuchunwei")
- 'w-u-c-h-u-n-w-e-i'
- >>> "|".join(["hello","good","hi"])
- 'hello|good|hi'
- >>>
- >>> "chunwei".ljust(15,'-') #以-符号右填充共15个字符
- 'chunwei--------'
- >>>
- >>> "chunwei".rjust(15,'-') #以-符号左填充共15个字符
- '--------chunwei'
- >>>
- >>> "ChunWei".lower() #将大写变小写
- 'chunwei'
- >>> "CHUNWEI".lower()
- 'chunwei'
- >>>
- >>> " wu \n".rstrip() #去右空格
- ' wu'
- >>> "\n wuchunwei \n".rstrip()
- '\n wuchunwei'
- >>>
- >>> "\n wu \n".lstrip() #去左空格
- 'wu \n'
- >>> " \n wuchunwei ".lstrip()
- 'wuchunwei '
- >>>
>>> name="wuchunwei"
>>> name.rstrip('i')#右边指定字符串
'wuchunwe'
>>> name.rstrip('ei')
'wuchunw'
>>> name.rstrip('wi')
'wuchunwe'
>>> name.lstrip('w') #去左边指定字符串
'uchunwei'
>>> name.lstrip('wi')
'uchunwei'
>>> name.lstrip('u')
'wuchunwei'
>>>
- #等位替换(加密解密)
- >>> from_str = "!@#$%^&"
- >>> to_str = "abcdefg"
- >>> trans_table = str.maketrans(to_str,from_str)
- >>> print("backup".translate(trans_table))
- @!#kup
- >>>
- >>> "hello world 666 good".partition("w") #以指定字符分割成3份(指定的字符不存在以空分割)
- ('hello ', 'w', 'orld 666 good')
- >>> "hello world 666 good".partition("")
- ('hello world ', '', ' good')
- >>> "hello world 666 good".partition("z")
- ('hello world 666 good', '', '')
- >>>
- >>> "hello".replace("l","L") #以特定字符替换现有字符,可以设定替换次数(默认替换全部)
- 'heLLo'
- >>> "hello".replace("h","HHH")
- 'HHHello'
- >>> "hello".replace("l","L",1)
- 'heLlo'
- >>>
- >>> "wu\n chun\nwei".splitlines() #以\n分隔
- ['wu', ' chun', 'wei']
- >>> "\nwuchun\nwei".splitlines()
- ['', 'wuchun', 'wei']
- >>> "\nwuchun\nwei".split("u") #以指定的字符分割(保留特殊字符)
- ['\nw', 'ch', 'n\nwei']
- >>>
- #计数器
import collections
obj = collections.Counter('zzzfcsdvc,dasdwezzrggfdgeqwewewe')
print(obj)
""" 结果: C:\Python35\python.exe D:/Python代码目录/Python_codeing/caixing_codeing/day3/有序字典.py
Counter({'z': 5, 'e': 5, 'w': 4, 'd': 4, 'g': 3, 'f': 2, 's': 2, 'c': 2, 'r': 1, ',': 1, 'q': 1, 'v': 1, 'a': 1}) """
字典(dict)
字典是一种key-value的数据类型,使用就像上学时用的字典,可以通过笔划、字母来查对应页的详细内容
语法:
- info = {
- 'stu1101': "Chunwei Wu",
- 'stu1102': "Mengmeng Yang",
- 'stu1103': "Qi Wei",
- }
字典的特性:
- 1)dict是无序的
- 2)key必须是唯一的,so 天生去重
快速定义一个字典(fromkeys)
- ###实例代码:
- dic1=dict.fromkeys('abc',) #分别以a、b、c为key,1为value为键值创建字典(去重)
- print("dict1===>",dic1)
- dic2=dic1.fromkeys('hello',)
- print("dict2===>",dic2)
- dic3=dict.fromkeys([,,],{'names':'weige','age':})
- print("dict3===>",dic3)
- ###运行结果:
- C:\Python35\python.exe D:/Python代码目录/day3/字典.py
- dict1===> {'a': , 'b': , 'c': }
- dict2===> {'l': , 'o': , 'e': , 'h': }
- dict3===> {: {'age': , 'names': 'weige'}, : {'age': , 'names': 'weige'}, : {'age': , 'names': 'weige'}}
- Process finished with exit code
字典的常见操作:
- ===》增加
- >>> info
- {'stu1101': 'Chunwei Wu', 'stu1103': 'Qi Wei', 'stu1102': 'Mengmeng Yang'}
- >>> info["stu1104"] = "吴春伟" #增加一个字典数值
- >>> info
- {'stu1101': 'Chunwei Wu', 'stu1103': 'Qi Wei', 'stu1104': '吴春伟', 'stu1102': 'Mengmeng Yang'} #字典是无序的
- >>>
- ===》修改
- >>> info
- {'stu1101': 'Chunwei Wu', 'stu1103': 'Qi Wei', 'stu1104': '吴春伟', 'stu1102': 'Mengmeng Yang'}
- >>> info['stu1104'] = "WUCHUNWEI" #修改(重新赋值)
- >>> info
- {'stu1101': 'Chunwei Wu', 'stu1103': 'Qi Wei', 'stu1104': 'WUCHUNWEI', 'stu1102': 'Mengmeng Yang'}
- >>>
- ===》删除
- >>> info
- {'stu1101': 'Chunwei Wu', 'stu1103': 'Qi Wei', 'stu1104': 'WUCHUNWEI', 'stu1102': 'Mengmeng Yang'}
- >>> info.pop("stu1104") #标准删除姿势(需要指定key键值)
- 'WUCHUNWEI'
- >>> info
- {'stu1101': 'Chunwei Wu', 'stu1103': 'Qi Wei', 'stu1102': 'Mengmeng Yang'}
- >>>
- >>> del info['stu1101'] #字典删除方式2
- >>> info
- {'stu1103': 'Qi Wei', 'stu1102': 'Mengmeng Yang'}
- >>>
- >>> info
- {'stu1101': 'Nginx', 'stu1103': 'Qi Wei', 'stu1105': 'PHP', 'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> info.popitem() #popitem随机删除
- ('stu1101', 'Nginx')
- >>> info
- {'stu1103': 'Qi Wei', 'stu1105': 'PHP', 'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> info.popitem()
- ('stu1103', 'Qi Wei')
- >>> info
- {'stu1105': 'PHP', 'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> info.popitem()
- ('stu1105', 'PHP')
- >>> info
- {'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>>
- ===》查找
- >>> info
- {'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> "stu1102" in info #标准用法
- True
- >>> info.get("stu1102") #获取(查找)
- 'Mengmeng Yang'
- >>> info["stu1102"] #第二种方法
- 'Mengmeng Yang'
- >>>
- >>> info.get("stu1108") #当查找一个不存在的字典key时:get方式为空不报错;第二种方式会报错
- >>> info["stu1108"]
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- KeyError: 'stu1108'
- >>>
- ===》更新
- >>> info
- {'stu1101': 'WeiGe', 'stu1102': 'Mengmeng Yang'}
- >>> user = {1:'a',2:'b',"stu103":"吴春伟"}
- >>> info.update(user)
- >>> info
- {'stu1101': 'WeiGe', 2: 'b', 1: 'a', 'stu103': '吴春伟', 'stu1102': 'Mengmeng Yang'}
- >>>
- ===》其他用法操作
- >>> info
- {'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> info.values() #获取字典的value值
- dict_values(['Apache', 'Mengmeng Yang'])
- >>>
- >>> info.keys() #获取字典的key值
- dict_keys(['stu1104', 'stu1102'])
- >>>
- >>> info
- {'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> info.setdefault("stu1102","WeiGe") #当原key存在不做改变(当key不存在时,新增一对key:value)
- 'Mengmeng Yang'
- >>> info
- {'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>> info.setdefault("stu1101","WeiGe") #当key不存在时,新增一对key:value(当原key存在不修改)
- 'WeiGe'
- >>> info
- {'stu1101': 'WeiGe', 'stu1104': 'Apache', 'stu1102': 'Mengmeng Yang'}
- >>>
- >>> info
- {'stu1101': 'WeiGe', 2: 'b', 1: 'a', 'stu103': '吴春伟', 'stu1102': 'Mengmeng Yang'}
- >>> info.items() #转换为列表
- dict_items([('stu1101', 'WeiGe'), (2, 'b'), (1, 'a'), ('stu103', '吴春伟'), ('stu1102', 'Mengmeng Yang')])
- >>>
两种取字典里的ke、value值得方式 (循环dict)
- ===》实例
- user = {
- "stu1101":"chunweiwu",
- "stu1102": "Mengmeng Yang",
- "stu1103": "Qi Wei",
- "stu1104": "Helen",
- }
- print("###方法1###")
- for key in user:
- print(key,user[key])
- print("###方法2(会先把dict转为list,大数据量是不推荐使用)###")
- for k,v in user.items():
- print(k,v)
- ===》结果
- C:\Python35\python.exe "D:/Python代码目录/day 1/dict.py"
- ###方法1###
- stu1104 Helen
- stu1102 Mengmeng Yang
- stu1103 Qi Wei
- stu1101 chunweiwu
- ###方法2(会先把dict转为list,大数据量是不推荐使用)###
- stu1104 Helen
- stu1102 Mengmeng Yang
- stu1103 Qi Wei
- stu1101 chunweiwu
- Process finished with exit code 0
深浅拷贝(copy|deepcopy)
- import copy
- ###浅拷贝
- copy.copy()
- ###深copy
- copy.deepcopy()
- 实例:
- dic1={'name':'weige','age':,'gfs':["MwngQi","Roses","Helly"]}
- dic2=dic1
- dic3=copy.copy(dic1) #字典里的浅copy就是copy模块里的copy
- print(dic1)
- print(dic2)
- print(dic3)
- 结果:
- C:\Python35\python.exe D:/Python代码目录/day3/字典.py
- {'gfs': ['MwngQi', 'Roses', 'Helly'], 'name': 'weige', 'age': }
- {'gfs': ['MwngQi', 'Roses', 'Helly'], 'name': 'weige', 'age': }
- {'gfs': ['MwngQi', 'Roses', 'Helly'], 'name': 'weige', 'age': }
- Process finished with exit code
- ###代码###
- info ={
- 'cpu':[80,],
- 'disk':[90,],
- 'mem':[85,]
- }
- print("befo===> ",info)
- print("======copy======")
- info_c=copy.copy(info)
- info_c['mem'][0]=100
- print("befo===> ",info)
- print("copy===> ",info_c)
- print("======deepcopy======")
- info_dc=copy.deepcopy(info)
- info_dc['cpu'][0]=50
- print("befo===> ",info)
- print("deepcopy===> ",info_dc)
- ###结果###
- C:\Python35\python.exe D:/Python代码目录/day3/字典.py
- befo===> {'mem': [85], 'cpu': [80], 'disk': [90]}
- ======copy======
- befo===> {'mem': [100], 'cpu': [80], 'disk': [90]}
- copy===> {'mem': [100], 'cpu': [80], 'disk': [90]}
- ======deepcopy======
- befo===> {'mem': [100], 'cpu': [80], 'disk': [90]}
- deepcopy===> {'mem': [100], 'cpu': [50], 'disk': [90]}
- Process finished with exit code 0
硬件参数copy与deepcopy事例
集合(set)
集合是一个无序的、不重复的数据组合,主要作用如下:
1)去重:把一个列表变成集合,就自动去重了
2)关系测试:测试两组数据之前的交集、差集、并集等测试
集合的常见内置方法
- ###交集:取共有部分
- stu_1={'hello','weige','monkey','kitty'}
- stu_2={'weige','mengqi','tiger'}
- print(stu_1&stu_2)
- print(stu_1.intersection(stu_2))
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {'weige'}
- {'weige'}
- Process finished with exit code
- ###并集:取包含两个集合所有的元素
- num_1={,,,,}
- num_2={,}
- ##并集:取包含所有的
- print(num_1|num_2)
- print(num_1.union(num_2))
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {, , , , }
- {, , , , }
- Process finished with exit code
- ###差集:用集合1中减去集合2中有的,剩余的就为集合1与集合2的差集
- num_1={,,,,}
- num_2={,}
- print(num_1-num_2)
- print(num_1.difference(num_2))
- print(num_2-num_1) #没有这为空
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {, , }
- {, , }
- set()
- Process finished with exit code
- ###对称差集:集合1与集合2所有的减去两者共有的剩下所有
- num_1={,,,,}
- num_2={,}
- print(num_1^num_2)
- print(num_1.symmetric_difference(num_2))
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {, , }
- {, , }
- Process finished with exit code
- ###子集:小于等于,返回布尔值;True和False
- num_1={,,,,}
- num_2={,}
- print(num_1<=num_2)
- print(num_1.issubset(num_2))
- print(num_2.issubset(num_1))
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- False
- False
- True
- Process finished with exit code
- ###父集:大于等于
- num_1={,,,,}
- num_2={,}
- print(num_1>=num_2)
- print(num_1.issuperset(num_2))
- print(num_2.issuperset(num_1))
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- True
- True
- False
- Process finished with exit code
集合其他内置方法
- ###更新update
- s1={1,2,3}
- s1.update('e')
- s1.update((1,2,3,4))
- s2={'h','e','l'}
- s1.update('hello')
- print(s1)
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {'h', 1, 2, 3, 4, 'o', 'l', 'e'}
- Process finished with exit code 0
- ###增加add
- s1={1,2,3}
- s1.add('hello')
- print(s1)
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {1, 2, 3, 'hello'}
- Process finished with exit code 0
- ###随机删除pop
- s1={1,2,3}
- s1.pop()
- print(s1)
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {2, 3}
- Process finished with exit code 0
- ###指定删除(元素不存在则报错)
- s1={1,2,3}
- s1.remove('w')
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- Traceback (most recent call last):
- File "D:/Python代码目录/day3/集合.py", line 88, in <module>
- s1.remove('w')
- KeyError: 'w'
- Process finished with exit code 1
- ###删除元素不存在的集合不报错的删除方式
- s1={1,2,3}
- print(s1.discard('a'))
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- None
- Process finished with exit code 0
- ###差集更新(s1=s1-s2)
- s1={1,2,5,'a','c'}
- s2={1,2}
- s1.difference_update(s2)
- print(s1)
- C:\Python35\python.exe D:/Python代码目录/day3/集合.py
- {5, 'a', 'c'}
- Process finished with exit code 0
Python之旅Day2 元组 字符串 字典 集合的更多相关文章
- Python中列表,元组,字典,集合的区别
参考文档https://blog.csdn.net/Yeoman92/article/details/56289287 理解Python中列表,元组,字典,集合的区别 列表,元组,字典,集合的区别是p ...
- Python基础-列表、元组、字典、字符串
Python基础-列表.元组.字典.字符串 多维数组 nums1 = [1,2,3] #一维数组 nums2 = [1,2,3,[4,56]] #二维数组 nums3 = [1,2,3,4,['a ...
- python学习笔记(一)元组,序列,字典
python学习笔记(一)元组,序列,字典
- Python中列表、元组、字典、集合与字符串,相关函数,持续更新中……
本篇博客为博主第一次学 Python 所做的笔记(希望读者能够少点浮躁,认真阅读,平心静气学习!) 补充: 列表.元组和字符串共同属性: 属于有序序列,其中的元素有严格的先后顺序 都支持双向索引,索引 ...
- Python 全栈开发二 python基础 字符串 字典 集合
一.字符串 1,在python中,字符串是最为常见的数据类型,一般情况下用引号来创建字符串. >>ch = "wallace" >>ch1 = 'walla ...
- python基础语法3 元组,字典,集合
元组: ========================元组基本方法===========================用途:存储多个不同类型的值定义方式:用过小括号存储数据,数据与数据之间通过逗号 ...
- python数据类型详解及列表字典集合推导式详解
一.运算符 Python语言支持以下类型的运算符: 算术运算符 如: #!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = 6 print(a ...
- Day 15 python 之 列表、元组、字典
基础: #! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "DaChao" # Date: 2017/6/ ...
- Python学习---列表,元组,字典
### 列表 list = [1,2,3,4,5,6] list.append(7) print(list) ===>>> [1, 2, 3, 4, 5, 6, 7] list[2] ...
随机推荐
- 一致性hash算法及java实现
一致性hash算法是分布式中一个常用且好用的分片算法.或者数据库分库分表算法.现在的互联网服务架构中,为避免单点故障.提升处理效率.横向扩展等原因,分布式系统已经成为了居家旅行必备的部署模式,所以也产 ...
- leetcode每日刷题计划-简单篇day2
今天数模比赛爆肝&操作系统大作业 脖子疼orz先把题过了保证flag不倒..个别细节回头看吧 Num 13 罗马数字转整数 Roman to Integer 一遍提交过,开始编译出了点问题 具 ...
- 富文本编辑器summerNote
载入富文本: $('.summernote').summernote({ height: 220, tabsize: 2, lang: 'zh-CN' }); 富文本获取内容: $('.summern ...
- java书籍
1.«java高并发编程详解 »一本比较详细介绍多线程的书籍,个人感觉比 并发编程思想 这本书详细
- git command line 提交代码
echo "# spring-boot-apollo-demo" >> README.md git init git add README.md git commit ...
- 特大数字之和,返回结果是字符串(考虑到数字特别大,如果相加会产生e)
自己做的,没有整理代码,还是做出来了: 做这个题时,最总要的一步思路就是,先让长度一致,然后从个位开始,每一个与每一个数字相加,如果大于10,则下一次另外两个数相加时加1 function add(a ...
- centos7下面添加htop工具
htop下载wget http://sourceforge.net/projects/htop/files/latest/download 解压tar -zxf downloadcd htop-1.0 ...
- gitlab 常用维护命令
GitLab简介 GitLab 是一个用于仓库管理系统的开源项目.使用Git作为代码管理工具,并在此基础上搭建起来的web服务.Github是公共的git仓库,而Gitlab适合于搭建企业内部私有gi ...
- LR基础理论详解
本人参考了大神的博客(https://blog.csdn.net/cyh_24/article/details/50359055),写的非常详细,在此整理一下要点 逻辑斯蒂分布 基础公式了解 二项逻辑 ...
- java基础 ------- 多重循环 and break与continue
----- 什么是多重循环 ---- 打印数列 public class ForEx { public static void main(String[] args){ for(int i = ...