目录
1、python中常见序列
2、序列的基本操作
3、序列的转换
作者:
编辑:
版本:
someone
xiaoluo
python3
python中常见序列(serial)
python中常见的序列有:字符串、列表(list)、元组(tuple)、集合(set)、字典(dict)
有如下一些特点:
1) 除集合外,均可索引,索引值从0开始
2) 除集合外可以通过切片得到一个范围内元素的集合
3) 有很多共同的操作(重复操作符、拼接操作符、成员关系符等)
序列的基本操作
前面已经介绍了列表、元组和字典,下面简单介绍字符串和集合的操作
1) 字符串
字符串索引、切片等操作同list
>>> a ='The is a sample'
>>> a[]
'T'
>>> a[-1]
'e'
>>> a[3:5]
' i'
>>> a[4:6]
'is'
>>> a[-3:]
'ple'
2) 集合(set)
集合常用{}表示,如:
>>> a = {1,2,3,4,5}
集合中元素会自动去重,即无重复值
>>> b = {1,2,3,4,1,2,3,6,7,8}
>>> b
{1,2,3,4,6,7,8}
集合无法索引和切片,但可以对其求最大值、最小值和长度等操作
>>> b = {1,2,3,4,1,2,3,6,7,8}
>>>max(b)
8
>>>min(b)
1
>>>len(b)
7
>>>sum(b)
31
序列的转化
1) 字符串转list: list(字符串),转tuple: tuple(字符串),转set: set(字符串)
>>> a ='this is a story'
>>>list(a)
['t','h','i','s',' ','i','s',' ','a',' ','s','t','o','r',
'y']
>>>tuple(a)
('t','h','i','s',' ','i','s',' ','a',' ','s','t','o','r',
'y')
>>>set(a)
{'a','h','t','o','r','s',' ','y','i'}
2) list转字符串: ''.join(字符串),转tuple:tuple(list),转set: set(list)
>>> a = ['the','school']
>>>''.join(a)
'theschool'
>>> a = ['1','2','3']
>>>''.join(a)
'123'
>>>tuple(a)
('1','2','3')
>>>set(a)
{'1','2','3'}
3) tuple转list:list(tuple),转set:set(tuple),转字符串: ''.join(tuple)
>>> a = ('1','2','3','4','5','6')
>>>list(a)
['1','2','3','4','5','6']
>>>set(a)
{'6','4','3','2','5','1'}
>>>''.join(a)
'123456'
4) set转list: list(set),转tuple: tuple(set),转字符串:''.join(set)
>>> a = {'1','2','3','4','5','6'}
>>>list(a)
['6','4','3','2','5','1']
>>>set(a)
{'6','4','3','2','5','1'}
>>>''.join(a)
'643251'
5) dict需要key和value值,可以转化为其他几种序列,但其他序列不可转化为dict
>>> dict = {'char':1,'list':2,'set':3,
'tuple':4,'dicy':5}
>>>str(dict)
"{'char': 1, 'list': 2, 'set': 3, 'tuple': 4,
'dicy': 5}"
>>>list(dict)
['char','list','set','tuple','dicy']
>>>set(dict)
{'char','tuple','dicy','list','set'}
>>>tuple(dict)
('char','list','set','tuple','dicy')
思考
尝试计算字符串中指定字符出现的次数,如:’this is a problem’,’t’出现1次
python基础系列目录
★
基本概念
常量及变量
数据类型
数据类型转化
运算符
运算符
运算符优先级
数据结构
列表
元组
字典
序列
控制流
if语句
while语句
for循环
break语句
continue语句
函数
函数形参
局部变量
默认参数值
关键参数
return语句
字符串文档
配套教学视频
本系列练习可以配合计算机二级视频一起食用,观看地址为:
https://study.163.com/course/introduction.htm?courseId=1006044085
领取专属 10元无门槛券
私享最新 技术干货