四 列表
1、列表是什么
列表由一系列按特定顺序排列的元素组成。列表让你能够在一个地方存储成组的信息。
在Python中,用方括号[]来表示列表,并用逗号来分隔其中的元素
numbers=[1,1,2,2,3,3]
print(numbers)
2.访问列表
要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。
注意:从前往后,索引排序从0开始
numbers=[1,1,2,2,3,3]
print(numbers)
print(numbers[0])
还可以对查询的列表元素使用字符串方法
比如
print(numbers[0].title()]
访问最后一个元素,可将索引指定为-1 (倒数第1,倒数第2用-1,倒数第3用-3,从后往前以此类推)
print(numbers[-1])
3.使用列表元素的值,拼接创建消息
transport=["bike","subway","bus","car"]
message=("I go to work by "+transport[2]+".")
print(message)
4.增删改元素
#修改:
transport=["bike","subway","bus","car"]
transport[2]="motorcycle"
print(transport)
#添加
#1.添加到末尾,方法append
transport=["bike","subway","bus","car"]
transport.append("motorcycle")
print(transport)
#方法append()让动态地创建列表易如反掌
transport=[]
transport.append("motorcycle")
transport.append("bus")
transport.append("bike")
print(transport)
#2.插入,用方法insert(索引,值),指定索引和值
transport=["bike","subway","bus","car"]
transport.insert(2,"motorcycle")
print(transport)
#删除
#1.del语句,需要知道被删除元素的索引/位置
transport=["bike","subway","bus","car"]
del transport[0]
print(transport)
#2.方法op(),删除列表末尾的元素
transport=["bike","subway","bus","car"]
transport.pop()
print(transport)
#并让你能够接着使用它,用poped(),需要对弹出的值进行定义
transport=["bike","subway","bus","car"]
popped_transport=transport.pop()
print(popped_transport)
print("Last time, I went home by "+popped_transport+" .")
#方法pop(索引),可以删除/弹出列表任何位置的元素
transport=["bike","subway","bus","car"]
popped_transport=transport.pop(1)
print(popped_transport)
print("Last time, I went home by "+popped_transport+" .")
#3.根据值删除元素,方法remove(值)
transport=["bike","subway","bus","car"]
transport.remove("bike")
print(transport)
#使用remove()从列表中删除元素时,也可接着使用它的值,需要对这个值进行定义
transport=["bike","subway","bus","car"]
too_slow="bike"
transport.remove(too_slow)
print(transport)
print("I don't like "+too_slow+" because it's too slow.")
#注意:方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。