集合数据类型

非数字型

列表[](其他语言叫数组)

注意点:第一个成员的索引编号为0,不能访问不存在的索引编号

python 复制代码
# list是列表变量名,列表中有三个成员
list=['刘备','曹操','关羽']
print(list[0])
print(list[1])
print(list[2])
print(list[3]) # 如果显示一个列表没有的成员,会报错

空列表定义

python 复制代码
list2=[] #定义一个空列表list2变量
print(list2[0]) # 对于空列表不能访问成员

查看列表所有方法

python 复制代码
print(dir(list))

列表中常用方法

insert(位置索引,要插入的值):列表中指定位置插入值

python 复制代码
list=['刘备','曹操','关羽']
list.insert(1,'吕布')
print(list)    # ['刘备', '吕布', '曹操', '关羽']

append(插入的值):末尾添加数据

python 复制代码
list=['刘备','曹操','关羽']
list.insert(1,'吕布')
list.append('张飞')
print(list)    # ['刘备', '吕布', '曹操', '关羽', '张飞']

extend(列表名):把一个列表的成员追加到指定列表的后面

python 复制代码
list=['刘备','曹操','关羽']
list.insert(1,'吕布')
list.append('张飞')
print(list)

list2=['周瑜','鲁肃']
list.extend(list2)
print(list)    # ['刘备', '吕布', '曹操', '关羽', '张飞', '周瑜', '鲁肃']

index(数据,起始位置):起始位置可以不写默认从0开始,也可以指定位置寻找,查找不到数据的话,会报错

python 复制代码
list=['刘备','曹操','关羽']
list.insert(1,'吕布')
list.append('张飞')
print(list)

list2=['周瑜','鲁肃']
list.extend(list2)
print(list)

print(list.index('关羽'))    # 3

list.sort(reverse=True):列表成员从大到小排序,即降序

list.reverse():颠倒列表成员顺序

列表推导式

列表变量名=[x for x in range(开始值,结束值,步长) if 条件]

python 复制代码
list[x for x in range(3,10,2)]
# 3 5 7 9

列表强转

python 复制代码
list=['张飞',1,4.5,'刘备']
i=1
for x in list:
    print('第%d个成员的值:%s' %(i,str(x)))
    i+=1

公共方法

元组()(与列表相似,不能修改)

python 复制代码
tuple1='张三',
tuple2=('张三',)
tuple3=('张三','李四')
tuple4='张三','李四'
tuple5=()
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
print(tuple5)

列表和元组可以相互转换:使用tuple(list1)和list(tuple1)

集合{} 无序 不允许重复

注意:如果想要创建一个空集合:set1=set()

字典{} 键值对

字典键名不能重复,键和值用冒号分隔

python 复制代码
dict={"name":"张三","age":20,"sex":"男"}
for n in dict:
    print(n,dict[n])

dict.items()得到一个元组

python 复制代码
dict={"name":"张三","age":20,"sex":"男"}
# for n in dict.items():
#    a,b=n
#    print(a,b)

for a,b in dict.items():
    print(a,b)

字符串

注意:不能通过[索引]的方式修改字符串中具体字符的值

find和replace使用

python 复制代码
str1="hello python"
a=str1.find("python")
print(a)
str2=str1.replace("python","java")
# str1没有改变,只是把str1中的python改为java给str2
print(str2)
print(str1)

去除空格使用

python 复制代码
str1="    aaaaaa       "
str2=str1.lstrip();
print("'%s'" %str2)
str3=str1.rstrip();
print("'%s'" %str3)
str4=str1.strip();
print("'%s'" %str4)

字符串格式化

python 复制代码
id=1
name="刘备"
weight=80.2
tel="13912345678"
print("%06d" %id)
print("姓名:%s" %name)
print("体重:%.3f:" %weight)
print("电话:%s" %tel)
print("*" *20)

切片

相关推荐
5:003 分钟前
云备份项目
linux·开发语言·c++
Eiceblue12 分钟前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_5275504025 分钟前
初级程序员入门指南
javascript·python·算法
笨笨马甲41 分钟前
Qt Quick模块功能及架构
开发语言·qt
程序员的世界你不懂1 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
夜晚回家1 小时前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS3141 小时前
C++动态规划-01背包
开发语言·c++·动态规划
前端页面仔1 小时前
易语言是什么?易语言能做什么?
开发语言·安全
CryptoPP1 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@1 小时前
Python数据分析7
开发语言·python