python数据类型 (列表list)
python数据类型 (列表list)
1 定义
#同字符串一样,索引取头不取尾
#直接在原列表经行修改,不创建新列表,与字符串不同
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
2 方法
注:list方法均不生成新数列
1 增加
-
追加 (.append())
list1 = ['Google', 'Runoob', 1997, 2000] list1.append(123) print(list1) #输出:['Google', 'Runoob', 1997, 2000, 123] -
插入 (.insert())
list1 = ['Google', 'Runoob', 1997, 2000] list1.insert(2,666) print(list1) #输出:['Google', 'Runoob', 666, 1997, 2000] -
合并 (.extent())
list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list1.extend(list2) print(list1) #输出:['Google', 'Runoob', 1997, 2000, 1, 2, 3, 4, 5]注:合并与追加,插入的区别
#追加 (.append()) #追加一个数列 list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list1.append(list2) print(list1) #输出:['Google', 'Runoob', 1997, 2000, [1, 2, 3, 4, 5]]#插入 (.insert()) list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list1.insert(4,list2) #效果同上 print(list1) #输出:['Google', 'Runoob', 1997, 2000, [1, 2, 3, 4, 5]]#合并 (.extent()) list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list1.extend(list2) print(list1) #输出:['Google', 'Runoob', 1997, 2000, 1, 2, 3, 4, 5]
2 修改
list1 = ['Google', 'Runoob', 1997, 2000]
list1[1] = "abc"
print(list1) #输出:['Google', 'abc', 1997, 2000]
3 删除
-
del (del list())
list1 = ['Google', 'Runoob', 1997, 2000] del list1[1] print(list1) #输出:['Google', 1997, 2000] -
pop (.pop())
#有返回值,返回被删除的值 #默认删除最后一项,等同 list1.pop(-1) list1 = ['Google', 'Runoob', 1997, 2000] v1 = list1.pop() print(list1) #输出:['Google', 'Runoob', 1997] print(v1) #输出:2000#删除指定项 list1 = ['Google', 'Runoob', 1997, 2000] v1 = list1.pop(0) print(list1) #输出:['Runoob', 1997, 2000] print(v1) #输出:Google -
clear (.clear())
list1 = ['Google', 'Runoob', 1997, 2000] list1.clear() print(list1) #输出:[]
4 查找 (.index())
#有返回值,返回索引值
#默认输出第一个值的索引值
list1 = ['Google', 'Runoob', 1997, 2000,1997]
v1 = list1.index(1997)
print(v1) #输出:2
#输出一定片段的第一个值
list1 = ['Google', 'Runoob', 1997, 2000,1997,'Runoob','Google']
v1 = list1.index(1997,3) #从第4位开始
print(v1) #输出:4
5 统计 (.count())
#有返回值,返回次数
#统计字符出现的次数
list1 = ['Google', 'Runoob', 1997, 2000,1997]
v1 = list1.count(1997)
print(v1) #输出:2
6 切片
list1 = ['Google', 'Runoob', 1997, 2000,1997]
v1 = list1[1:2]
print(v1) #输出:['Runoob']
3 运算
1 字符运算
"+" "*"与字符串相同
2 for遍历
list1 = ['Google', 'Runoob', 1997, 2000,1997]
for num in list1:
print(num)
浙公网安备 33010602011771号