python的学习笔记/002-3(20

2020-01-10 10:51:25 浏览数 (1)

群集类型

群集类型

列表

元组

字典

集合

list

tuple

dict

set

1.列表 列表的类型是list,特点为有序,具备索引,内容与长度可以变动。要创建列表,可以使用[]直接表示法,列表中每个元素使用逗号分隔开。 列表的常见操作 (1) 元素的切片

代码语言:javascript复制
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Mashu","Zhaoyun"]
print(names)
print(names[0])    # 切位置0的元素
print(names[0:4])  #  切出位置0~3的元素
print(names[-1])     # 切出最后一位的元素
print(names[-3:])     # 切片,左取右不取``

print(names[0:-1:2])    # 有间隔的切片

for i in names:
    print(i)           # 循环的切片方法,这个i就代表了列表中的元素

(2) 列表的增,改,删 names.append();names.insert();names.remove();names.pop()

代码语言:javascript复制
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)

names.append("Zhugelaing")   # [增]-----在列表末尾  追加  诸葛亮
print(names)
names.insert(3,"daqiao")       # [增]-----在列表中的位置3  插入  大乔
print(names)

names[2]="zhouyu"            #[改]----- 将刘备  替换  为周瑜
print(names)   

# names.remove("Masu")      # [删]-----删除 马谡 (有三种常用的方法)
# del names[-3]
print(names.pop(-3))
print(names)

(3) 列表的查,统计 names.index();names.count()

代码语言:javascript复制
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)

print(names.index("Zhaoyun"))         # 获取下标,赵云有俩个但是却只查到了列表里的第一个????
print(names[names.index("Zhaoyun")])

print(names.count("Zhaoyun") )     #   统计  列表中赵云的个数

(4) 列表的反转,排序,合并 names.reverse();names,sort();names.extend()

代码语言:javascript复制
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)
names.reverse()    #  将列表  反转
print(names)
names.sort()    # 将列表按照默认的utf-8格式  排序
print(names)
names2=["Chaochao","Simayi","Diewei","Xiahuodong","Xuchu"]
names.extend(names2 )       #  合并俩个列表,但是合并的列表仍然存在
print(names)

(5) 列表的复制 names.copy();copy.copy();copy.deepcopy()

代码语言:javascript复制
import copy  # 需要为深copy引入模块

names=["Zhangfei","Guanyu","Liubie","Zhaoyun",["zhouyu","daqiao"],"Machoa","Jiangwei","Masu","Zhaoyun"]

names1=names    #  完全就是二者相等

names2=names.copy()   # 浅copy,第二个列表里其实copy的是一个地址,可以用来实现一个联合账户的功能
names3=copy.copy(names) # 三种不同的实现方法
names4=names[:]

names5=copy.deepcopy(names)   #  深copy一般不用因为会占用更多的空间

names[2]="刘邦"     #  将位置2的元素改为刘邦
names[4][0]="小乔"   # 将位置4列表里的位置0元素改为大乔

print(names)   # 比较几种不同的复制
print(names1)
print(names2)
print(names3)
print(names4)
print(names5)

(6) 列表的清除 names.clear()

代码语言:javascript复制
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)
names.clear()
print(names)

0 人点赞