首页 > 编程语言 >【Python无伤速通】第二话:容器

【Python无伤速通】第二话:容器

时间:2023-04-20 15:23:57浏览次数:43  
标签:输出 速通 无伤 Python list 字符串 dict str print

目录

容器

容器

序列

序列包括:

列表 list
字符串 str
元组 tuple
字节序列 bytes


返回目录

序列_索引

索引有正负之分,正索引自左向右从0开始,负索引自右向左从-1开始。

0 1 2 3 4
H a p p y
-5 -4 -3 -2 -1


返回目录


序列_加和乘

s1="bi"
s2="li"
s3=s1+s2
print(s3)
s3*=2
print(s3)
# 输出:
# bili
# bilibili


返回目录


序列_切片

slicing是从某序列切分出子序列




语法形式:

str[start : end : step]
# 从区间[start,end)切分出子串


start 开始索引,缺省值为0
end 结束索引,缺省值为容器长度(比如长度为3,即容器内含3个元素,
那么正索引为0,1,2,由于“左开右闭”所以end默认为3)
step 顾名思义,可根据下例理解
s="hello world"
print(s[:]) # 输出:hello world
print(s[: : 2]) # 输出:hlowrd
print(s[0 : 11 : 2]) # 输出:hlowrd
print(s[0 : 6 : 1]) # 输出:hello




返回目录

成员测试

a="abcdefg"
print('a' in a)
print('h' in a)
# 输出:
# True
# False

返回目录

列表

列表_容器的概念

列表作为一种容器,和数列不同的是前者可以装不同类型的数据。

list=[1,"123",['o','k']]
print(list)
for item in list:
    print(item)
# 输出:
# [1, '123', ['o', 'k']]
# 1
# 123
# ['o', 'k']

列表_创建

列表是可变序列类型。支持插入、删除、替换、追加。

list0=[]    # 创建空列表
list1=[1,2,3,4] 
list2=[1]   # 创建只有一个元素的列表(异于后续只有一个元素的元组)

print(list0,type(list0),sep="   Its type: ")
print(list1)
print(type(list2))

# 输出:
# []   Its type: <class 'list'>
# [1, 2, 3, 4]
# <class 'list'>

转化

值得注意的是,除了上面创建列表的方式得到列表,还可以通过list()来转化得到列表。

str="China"
t=list(str)
print(t)
# 输出:
# ['C', 'h', 'i', 'n', 'a']

返回目录

列表_操作


列表_追加

a=[1,2,3]
a.append(4) # 追加单个元素
print(a) # 输出:[1, 2, 3, 4]
#-------------------------------------------
a=a+[5,6,7,8] # 追加多个元素的两种方法
print(a) # 输出:[1, 2, 3, 4, 5, 6, 7, 8]
a.extend(a)
print(a) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]

a.extend([9,10])
print(a) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

列表_插入

list.insert(参数1,参数2)
// 参数1表示新索引
// 参数2表示要插入的元素
list = [1,2,3,5]
list.insert(3,4) # 把元素4插入到索引为3的位置
print(list) 
# 输出:
# [1, 2, 3, 4, 5]

列表_修改

list = [1,2,3,5]
list[3]=4
print(list)
print(list[3])
# 输出:
# [1, 2, 3, 4]
# 4

列表_删除

list.remove(x) # 从列表中删除x
# 如果找到x,则删除
# 如果找到多个匹配值,则删除第一个匹配的x
list = [1,2,3,3,3,4,5]
list.remove(3)
print(list)

# 输出:
# [1, 2, 3, 3, 4, 5]

返回目录


元组

元组_介绍

想对元组存在的意义有初步理解可以先浏览锚点:元组_用途。

元组即tuple,是种有序列表,元素不能修改

元组
元素不能修改 没有append() 没有insert()


返回目录

元组_示例

the_tuple = (1,2,3,4) # 写在圆括号之间
print(type(the_tuple))
# 输出:
# <class 'tuple'>
the_tuple01 = (1) 
the_tuple02 = (1,)
print(type(the_tuple01))
print(type(the_tuple02))
# 输出:
# <class 'int'>
# <class 'tuple'>
nums = (1,2,[3,4])
print("改动前:"+str(nums))
print("请输入:")
nums[2][0]=int(input())
print("改动后:"+str(nums))
# 输出:
# 改动前:(1, 2, [3, 4])
# 请输入:
# 99
# 改动后:(1, 2, [99, 4])


返回目录

元组_创建

两种方法:直接定义、tuple函数转化而得

a = (1,2,3,4,5)
for item in a:
    print(item)
# 输出:
# 1
# 2
# 3
# 4
# 5
list = [1,2,3,4,5]
tu = tuple(list)
print(tu)
# 输出:
# (1, 2, 3, 4, 5)




元组_拆包

将一系列数据(类型可以各不相同)放入容器内的这个操作叫做“打包”;反之,将容器内的数据存入不同的变量中去叫做“拆包”。

user_id, user_name = (100037, "Benjamin")
print(user_id,user_name)
# 输出:
# 100037 Benjamin

元组_用途

在数据分析中,用来存储不能修改的数据。如:用户性别、用户身份证id等。





返回目录



bytes

主要用于网络通信,先挖个坑,日后细说

https://www.cnblogs.com/manongajie/p/12925801.html

返回目录



字符串

字符串的表示方式

普通字符串、原始字符串、长字符串

普通字符串

用引号(单引号或者双引号)括起来的字符串。

str="make China great again"
print(str)
  • 单双引号灵活的交错使用,可以用来表示引述内容。这样一来也无需转义了。
str='"机器学习"是一项严谨的科学哲理'
print(str)
# 输出:
# "机器学习"是一项严谨的科学哲理

原始字符串

使转义字符无效化。

common_str="hello\nworld"
raw_str=r"hello\nworld"
print(common_str)
print("***********************")
print(raw_str)
# 输出:
# hello
# world
# ***********************
# hello\nworld

返回目录

长字符串

用于表示文章,其中包含了换行、缩进等排版字符。对于长字符串,使用三引号括起来。

s = '''

Your confession remains to be my final pleading

But the only thing that's here with me

Is tic tac tic tac tic tac tic tac'''

print(s)

# 输出:
# Your confession remains to be my final pleading

# But the only thing that's here with me

# Is tic tac tic tac tic tac tic tac



返回目录

将字符串转化为数字

s='999'
t=int(s)
print(type(t))
# 输出:
# <class 'int'>


转换时制定基数(进制)
a='AB'
t=int(a,16)
print(type(t))
# 输出:
# <class 'int'>

将数字转换为字符串

a=1024
s=str(a)
print(type(s))
# 输出:
# <class 'str'>

格式化字符串

如果不用格式化字符串,用传统的拼接方式尽显累赘

i=32
s='i * i = '+str(i*i)
print(s)
# 输出:
# i * i = 1024

进入正题:字符串格式化输出

// 镜像类比:printf("%d + %d = %d",a,b,c)

占位符


默认占位符
i=32
s=' i * i = {}'.format(i*i) # {}是占位符,相当于c语言里的%d之类
print(s)
# 输出:
# i * i = 1024

参数序号占位符
a=1
b=99
s=' {0} + {1} = {2}'.format(a,b,a+b) 
print(s)
# 输出:
# 1 + 99 = 100

参数名占位符
a=1
b=99
s=' {p1} + {p2} = {p3}'.format(p1=a,p2=b,p3=a+b) 
print(s)
# 输出:
# 1 + 99 = 100





格式控制符

格式控制符 说明
s 字符串
d 十进制整数
f、F 十进制浮点数
g、G 十进制整数或浮点数
e、E 科学计数法表示浮点数
o 八进制整数
x、X 十六进制整数
{ 1 : d }
{1: d}
{1:d}

# 上述两种写法都可
# 1表示参数序号,d表示格式控制符



示例
price = 579.446
name ='RollsRoyce'
print('{0:s}的报价是{1:f}万元'.format(name,price))
print('{0:s}的报价是{1:e}万元'.format(name,price))

# 输出:
# RollsRoyce的报价是579.446000万元
# RollsRoyce的报价是5.794460e+02万元


返回目录

字符串操作

字符串操作
查找 替换 分割



查找

find函数在指定区间查找某个字符元素。如果找到则返回第一次出现的索引,未找到则返回-1。



str='aarabebccd'
print(str.find('r',0,3))
# 输出:
# 2
//上例第二个参数0和第三个参数3代表着一个这样的左闭右开区间:[0,3)



str='aarabebccd'
print(str.find('b'))
# 输出:
# 4
//上例b多次在字符串中出现,但是find函数只返回b第一次出现时的索引:4



替换

不说废话,自行体会。

str='0000'
print(str.replace('0','1',1),str.replace('0','1',2),str.replace('0','1',3),str.replace('0','1',4),sep='\n')
# 输出:
# 1000
# 1100
# 1110
# 1111



分割

将字符串以某个字符作为分隔符进行分割,分割函数split返回一个列表。

t = '1 23 456 7891'
print(t.split(' '))
# 输出:
# ['1', '23', '456', '7891']

如下例,也可设置参数maxsplit,控制分割的最大次数。若不设置,则默认分割所有(如上例,所有的空格都被用作分割符了)。
t = '1 1 1 1 1 1 1 1'
print(t.split(' ',maxsplit=3))
# 输出:
# ['1', '1', '1', '1 1 1 1 1']


返回目录


集合

可迭代,无序,去重

集合_创建

两种方式创建集合。

1.set()函数
2.{1,2,3,4}
list = [1,2,2,3,3]
set = set(list)
print(set)
# 输出:
# {1,2,3}



空集合创建的误区

a=set()
print(type(a))
# 输出:
# <class 'set'>
a={}
print(type(a))
# 输出:
# <class 'dict'>

返回目录


集合_操作

add(elem) 添加元素,如果元素已经存在,则不添加,不报错
remove(elem) 删除元素,如果元素不存在,则抛出错误
clear() 清除集合
s_set = {0,1,2,3,4,5}
s_set.add(6)
s_set.remove(0)
print(s_set)
s_set.clear()
s_set.add(999)
print(s_set)
# 输出:
# {1, 2, 3, 4, 5, 6}
# {999}


返回目录




字典

字典,顾名思义,给定拼音或者部首偏旁就有对应的页码。字典中存放的是映射。

字典_创建

1.dict()函数
2.{key1: value1, key2: value2, key3: value3}
stu_dict = {20211113191: '张三', 20211113198: '李四'}
print(stu_dict)
# 输出:
# {20211113191: '张三', 20211113198: '李四'}
stu_dict = dict({20211113191: '张三', 20211113198: '李四'})
print(stu_dict)
# 输出:
# {20211113191: '张三', 20211113198: '李四'}
s_dict = dict(zip([10011,10019],['Jackson','Lincoin']))
print(s_dict)
# 输出:
# {10011: 'Jackson', 10019: 'Lincoin'}

字典_由键索值

s_dict = dict(zip([10011,10019],['Jackson','Lincoin']))
print(s_dict[10019])
# 输出:
# Lincoin

字典_修改

字典支持添加、替换、删除。

字典_添加_替换

s_dict = dict(zip([10011,10019],['Jackson','Lincoin']))
s_dict[10011]='Bob' # 索引10011下有值则进行赋值
print(s_dict)
s_dict[10024]='Jimmy' # 索引下没有值,则添加该键值对到字典中
print(s_dict)
# 输出:
# {10011: 'Bob', 10019: 'Lincoin'}
# {10011: 'Bob', 10019: 'Lincoin', 10024: 'Jimmy'}

字典_删除

s_dict = dict(zip([10011,10019],['Jackson','Lincoin']))
print(s_dict.pop(10011))
print(s_dict)
# 输出:
# Jackson
# {10019: 'Lincoin'}


返回目录




访问字典视图

访问键值对、键、值。

s_dict = dict(zip([10011,10019],['Jackson','Lincoin']))
print(s_dict.items()) # 返回一个元组:dict_items([(10011, 'Jackson'), (10019, 'Lincoin')])
print(list(s_dict.items())) # 输出:[(10011, 'Jackson'), (10019, 'Lincoin')]

print(s_dict.keys())
print(list(s_dict.keys()))

print(s_dict.values())
print(list(s_dict.values()))

# 整体输出:
# dict_items([(10011, 'Jackson'), (10019, 'Lincoin')])
# [(10011, 'Jackson'), (10019, 'Lincoin')]
# dict_keys([10011, 10019])
# [10011, 10019]
# dict_values(['Jackson', 'Lincoin'])
# ['Jackson', 'Lincoin']

字典的遍历

s_dict = dict(zip([10011,10019,10089],['Tencent','Meituan','bilibili']))

print('------遍历键------')
for s_id in s_dict.keys():
    print(s_id)
print('------遍历值------')
for s_value in s_dict.values():
    print(s_value)
print('------遍历键值对------')
for s_id, s_value in s_dict.items():
    print('公司编号:{0}  公司名称:{1}'.format(s_id,s_value))

# 输出:
# ------遍历键------
# 10011
# 10019
# 10089
# ------遍历值------
# Tencent
# Meituan
# bilibili
# ------遍历键值对------
# 公司编号:10011  公司名称:Tencent
# 公司编号:10019  公司名称:Meituan
# 公司编号:10089  公司名称:bilibili


返回目录




容器_总结

列表 有序可变序列
元组 有序不可变序列
字典 无序可变
集合 无序去重(set可变,frozenset不可变)

序列(sequence)是有序的,字典和集合不属于序列。

标签:输出,速通,无伤,Python,list,字符串,dict,str,print
From: https://www.cnblogs.com/shinnyblue/p/17336997.html

相关文章

  • Python pth 文件写入 getshell 或权限维持
    今天看到Y4er师傅写的文章,我这里简单学习了一下:https://y4er.com/posts/python-pth-file-write-getshell/概述python的site模块支持"Site-specificconfigurationhook"的功能,这个功能点本身是用来将特定路径加入模块搜索路径。该模块在初始化期间自动导入。sys.prefix......
  • PYTHON - datetime 模块
    datetime模块1.1主要类date日期对象time时间对象datetime日期时间对象timedelta两个时间之间的时间间隔1.2date类date对象由year年份、month月份及day日期三个部分来构成的1.2.1获取当前日期fromdatetimeimportdatetime,datetoday=datetime.today().dat......
  • LeetCode Top100:回文链表 (python)
    LeetCodeTop100:回文链表给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。示例1:输入:head=[1,2,2,1]输出:true示例2:输入:head=[1,2]输出:false提示:链表中节点数目在范围[1,105] 内0<=Node.val<=9 ......
  • Python常用数据结构之元组
    前面的两节课,我们为大家讲解了Python中的列表,它是一种容器型的数据类型,通过列表类型的变量,我们可以保存多个数据并通过循环实现对数据的批量操作。当然,Python中还有其他容器型的数据类型,接下来我们就为大家讲解另一种容器型的数据类型,Python常用数据结构之元组(tuple)。元组的定义......
  • python dataclasses定义默认值为可变类型(转)
    原文:https://zhuanlan.zhihu.com/p/59658886作者:没有50CM手臂网站:知乎 场景还原最近开发遇到一个问题是在python3.7的dataclass中不能使用可变的默认值,错误如下:@dataclassclassFoo:bar:list=[]#ValueError:mutabledefault<class'list'>forfieldaisn......
  • python a股量化解决方案
    baostockhttp://baostock.com/baostock/index.php/A股K线数据pytdxhttps://rainx.gitbooks.io/pytdx/content/pytdx_reader.html......
  • LeetCode Top100: 相交链表(Python)
    LeetCodeTop100:相交链表给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。图示两个链表在节点 c1 开始相交:题目数据 保证 整个链式结构中不存在环。注意,函数返回结果后,链表必须 保持其原......
  • 【备忘录设计模式详解】C/Java/JS/Go/Python/TS不同语言实现
    简介备忘录模式(MementoPattern)是一种结构型设计模式。这种模式就是在不破坏封装的条件下,将一个对象的状态捕捉(Capture)住,并放在外部存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。备忘录模式常常与命令模式和迭代子模式一同使用。备忘录模式的角色有三个......
  • LeetCode Top100: 环形链表(python)
     给你一个链表的头节点 head ,判断链表中是否有环。如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从0开始)。注意:pos 不作为参数进行传递 。仅仅是为......
  • Python 图像处理实用指南:11~12
    原文:Hands-OnImageProcessingwithPython协议:CCBY-NC-SA4.0译者:飞龙本文来自【ApacheCN计算机视觉译文集】,采用译后编辑(MTPE)流程来尽可能提升效率。当别人说你没有底线的时候,你最好真的没有;当别人说你做过某些事的时候,你也最好真的做过。十一、深入学习图像处理——......