列表list
what
特定顺序排列的元素组成,元素之间可无特定关系
people =['Athna','Haqi','Mike','Romeo']
print(people)
how
访问 列表名+元素索引
print(people[1])
运行结果为Haqi’:
1.索引从0开始(本例索引为1,实际指向第二个元素)
2.python 只返回元素而不包含方括号或者引号
print(people[-1])
运行结果为Romeo,索引-1返回该列表最后一个元素
使用各个列表中的值
message='My best friend is '+people[0].title()+'.'
print(message)
输出结果:My best friend is Athna.
增、删、改元素
1. 修改
people[2]='John'
print(people)
运行结果:
[‘Athna’, ‘Haqi’, ‘John’, ‘Romeo’]
2. 添加
2.1末尾增加 append()方法
people.append('Amy')
print(people)
结果:[‘Athna’, ‘Haqi’, ‘Mike’, ‘Romeo’, ‘Amy’]
可以初始化列表为空逐个增加
people=[]
people.append('Amy')
print(people)
结果:[‘Amy’]
2.2 任意位置增加 insert()
people=['Athna', 'Haqi', 'John', 'Romeo']
people.insert(0,'Mike')
print(people)
结果:[‘Mike’, ‘Athna’, ‘Haqi’, ‘John’, ‘Romeo’]
3. 删除
3.1 del语句(已知索引)
del删除后无法再访问该元素
del people[0]
print(people)
结果 [‘Athna’, ‘Haqi’, ‘John’, ‘Romeo’]
3.2 pop()方法
3.2.1 删除(弹出)列表末尾的元素,并能够接着使用它(如同栈出栈顶)
people=['Athna', 'Haqi', 'John', 'Romeo']
print(people)
less_people=people.pop()
print(people)
print(less_people)
运行结果:
[‘Athna’, ‘Haqi’, ‘John’, ‘Romeo’]
[‘Athna’, ‘Haqi’, ‘John’]
Romeo
3.2.2 弹出列表中任意位置的值
pop(x):x为索引值
people=['Athna', 'Haqi', 'John', 'Romeo']
print(people)
less_people=people.pop(1)
print(people)
print(less_people)
运行结果
['Athna', 'Haqi', 'John', 'Romeo']
['Athna', 'John', 'Romeo']
Haqi
3.3 按值删除remove()
people=['Athna', 'Haqi', 'John', 'Romeo']
print(people)
people.remove('John')
print(people)
运行结果:
['Athna', 'Haqi', 'John', 'Romeo']
['Athna', 'Haqi', 'Romeo']
remove()只删除第一个指定的值,如果列表中出现多个,需要用循环判断删除剩余的指定值