- 创建列表 :[ ]表示列表,列表中的元素,无类型限制
bicycle=["trek","cannondale","redline","spe"]
print(bicycle)
print(bicycle[1])#访问列表第二个元素
print(bicycle[-1])#索引-1得到最后一个列表元素
print(bicycle[1].title())#title将元素变成首字母大写的
mix=[1,2,3,"xiaojiayu"]
print(mix)
运行结果:
[‘trek’, ‘cannondale’, ‘redline’, ‘spe’]
cannondale
spe
Cannondale
[1, 2, 3, ‘xiaojiayu’]
- 修改列表参数
bicycle=["trek","cannondale","redline","spe"]
bicycle[0]="honda"
print(bicycle)
运行结果:
[‘honda’, ‘cannondale’, ‘redline’, ‘spe’]
- 给列表添加新的元素
.append(只能添加一个元素在列表的末尾)
.extend([])以列表的形式添加在末尾
.insert(位置,元素)可以在任何位置插入元素
city=[]
city.append("beijing")
city.append("shanghai")
#city.append("shanghai","guangzhou","nanjing")#运行错误,append一次只能添加一个
print(city)
city.extend(["guangzhou","nanjing"])
print(city)
运行结果:
[‘beijing’, ‘shanghai’]
[‘beijing’, ‘shanghai’, ‘guangzhou’, ‘nanjing’]
city=["beiing","shanghai","guangzhou"]
city.insert(0,"nanjing")
print(city)
运行结果:[‘nanjing’, ‘beiing’, ‘shanghai’, ‘guangzhou’]
4.从列表中删除元素
.remove(“元素”)不需要知道具体位置,直接删除元素
del语句,删除整个列表 del city
.pop()弹出列表的最后一个元素,可以索引值,pop(2)弹出列表的第三个元素
city=["beijing","shanghai","guangzhou","nanjing"]
poped_city=city.pop(2)
print(city)
del city[0]
print(city)
print(poped_city)
结果:[‘beijing’, ‘shanghai’, ‘nanjing’]
[‘shanghai’, ‘nanjing’]
guangzhou
5.其他操作
count() 计算某个元素出现的次数
.index() 返回参数的位置.index(元素,start,stop)
.sort() 排序,默认从小到大排序 .sort(reverse=True)可以从大到小排序
.reverse() 颠倒元素顺序
list1=[1,1,2,3,4]
list1.count(1) #结果是2
list1.index(3) #结果是3
start=list1.index(1)+1
stop=len(list1)
list1.index(1,start,stop) #从list1中找到的1后面的元素开始,到列表结束,找到1的位置,是位置1
list2=[2,3,4,2,3,7,8,1,1,0]
print(list2)
list2.reverse()
print(list2)
list2.sort(reverse=True)
print(list2)
运行结果:
[2, 3, 4, 2, 3, 7, 8, 1, 1, 0]
[0, 1, 1, 8, 7, 3, 2, 4, 3, 2]
[8, 7, 4, 3, 3, 2, 2, 1, 1, 0]
- 缩进是python的灵魂
for 循环一定要注意冒号,才会有正确的缩进
for循环的一个小伙伴,range(start,stop,step)随机值函数,产生从start开始到stop-1,步长step的数值
citys=["beijing","shanghai","guangzhou","shenzhen"]
for each in citys:
print(each)
print("thank you!")
for i in range(1,8,1):
print(i)
结果:beijing
shanghai
guangzhou
shenzhen
thank you!
1
2
3
4
5
6
7
8. 列表分片(拷贝过程)list[开始位置:结束位置:步长]默认从0开始,步长为1,结束位置不包含
name1=name[:2]
name2=name[1:3]
name3=name[:]
print(name)
print(name1)
print(name2)
print(name3)
num1=[1,2,3,4,5,6,7]
print(num1)
print(num1[::2])#步长为2
print(num1[::-1])
num1.reverse()
print(num1)
运行结果:
[‘xiaohua’, ‘xioacao’, ‘xiaoming’, ‘xiaozhang’]
[‘xiaohua’, ‘xioacao’]
[‘xioacao’, ‘xiaoming’]
[‘xiaohua’, ‘xioacao’, ‘xiaoming’, ‘xiaozhang’]
[1, 2, 3, 4, 5, 6, 7]
[1, 3, 5, 7]
[7, 6, 5, 4, 3, 2, 1]
[7, 6, 5, 4, 3, 2, 1]