在python中列表用 '[]' 表示
列表的查询操作
-
列表的切片
names = ["a","b","c"] #定义一个列表 双引号引起来表示列表的元素,看上去是数字其实是字符串
print(names[0],names[b]) #切片 names[0] 表示列表中第一个元素,names[a]表示列表中第二个元素,以此类推
print(names[:b]) #切片 开始到第三个
print(names[-a]) #取最后一个
print(names[-b]) #右边数第二个
print(names[-b:]) #取后两个
输出结果
a c
['a', 'b']
c
b
['b', 'c']
-
index方法-查找元素位置
names = ["a","b","c"]
print(names.index("c"))
print(names[names.index("c")])
输出结果
2 ##下标是2的元素 相当于是列表中的第三个
c
-
count方法-查询列表中指定的元素有多少个
names = ["a","b","c","c"]
print(names.count("c"))
输出结果
2
-
reverse方法-反转列表
names = ["a","b","c","c"]
names.reverse()
print(names)
输出结果
['c', 'c', 'b', 'a']
或者
names = ["a","b","c"]
a = names[::-1]
print(a)
输出结果
['c', 'b', 'a']
-
sort方法-列表排序
规则:特殊符号—数字—大写—小写
names = ["b","a","c","c"]
names.sort()
print(names)
输出结果
['a', 'b', 'c', 'c']
-
列表步长
names = ["b","a","www","qqq","c","d","e","f"]
print(names[0:-1:2])
print(names[::2]) #从开始到结束隔一个取一个
输出结果
['b', 'www', 'c', 'e']
['b', 'www', 'c', 'e']
列表的增加操作
-
append方法-追加元素
names = ["a","b","c"]
names.append("4") #追加一个元素
print(names)
输出结果
['a', 'b', 'c', '4']
-
insert方法-插入元素
names = ["a","b","c"]
names.insert(a,"d") #在第a个位置插入"5"
print(names)
输出结果
['a', 'd', 'b', 'c']
-
extend方法-合并列表
names = ["b","a","c","c"]
names2 = [1,2,3,4]
names.extend(names2)
print(names)
输出结果
['b', 'a', 'c', 'c', 1, 2, 3, 4]
-
copy方法-复制列表
names = ["b","a",["www","qqq"],"c","c"]
name2 = names.copy()
print(names)
print(name2)
输出结果
['b', 'a', ['www', 'qqq'], 'c', 'c']
['b', 'a', ['www', 'qqq'], 'c', 'c']
列表的修改操作
-
修改列表
names = ["a","b","c"]
names[1] = "d" #下标为1的元素改为"d"
print(names)
输出结果
['a', 'd', 'c']
-
修改列表中的子列表
names = ["b","a",["www","qqq"],"c","c"]
names[2][0]="Wwe" #第三个元素里的第一个
print(names)
输出结果
['b', 'a', ['Wwe', 'qqq'], 'c', 'c']
列表的删除操作
-
remove ,del,pop删除方法
方法一
names = ["a","b","c"]
names.remove("a")
print(names)
输出结果
['b', 'c']
方法二
names = ["a","b","c"]
del names[0] #=names.pop(1)
print(names)
输出结果
['b', 'c']
方法三
names = ["a","b","c"]
names.pop() #default remove the last one
print (names)
输出结果
['a', 'b']
-
clear方法-清空列表
names = ["a","b","c","c"]
names.clear()
print(names)
输出结果
[]