列表(list)
用来存储不同的数据类型,使用 [ ]
与字符串的索引一样,list索引从0开始,可以进行截取、组合等操作
(一)访问列表中的元素
1.索引(与字符串的索引一样,list索引从0开始,按索引访问元素的值)
list1 = ['abc',1,2,'www','abcd']
print(list1[0]) ##正向取
# 返回值 abc
print(list1[2]) ##正向取
# 返回值 2
print(list1[-1]) ##反向取
# 返回值 abcd
2.重复输出列表中元素
list1 = ['abc','www']
print(list1 * 3) #输出三遍
# 返回 ['abc', 'www', 'abc', 'www', 'abc', 'www']
3.列表元素的连接
list1 = ['abc',1,2]
list2 = ['www','abcd']
print(list1+list2)
# 返回 ['abc', 1, 2, 'www', 'abcd']
(二)切片(顾头不顾尾,默认步长为1)
list1 = ['abc',1,2,'www','abcd']
print(list1[1:]) ##打印第一个元素之后的内容
# 返回 [1, 2, 'www', 'abcd']
print(list1[:-1]) ##打印最后一个元素之前的内容
# 返回 ['abc', 1, 2, 'www']
print(list1[::-1]) ##倒序输出
# 返回 ['abcd', 'www', 2, 1, 'abc']
(三)列表元素的增加、删除、更新
1.增加:
(1)append:往列表的末尾添加元素
list1 = ['abc',1,2]
list1.append('www')
print(list1)
# 返回 ['abc', 1, 2, 'www']
(2)insert(索引,元素):指定位置添加元素
list1 = ['abc',1,2,'www']
list1.insert(3,'python')
print(list1)
# 返回 ['abc', 1, 2, 'python', 'www']
(3)extend():往一个列表内添加多个元素,括号里放入列表
####方法一
list1 = ['abc',1,2,'www']
list1.extend(['python','hello'])
print(list1)
# 返回 ['abc', 1, 2, 'www', 'python', 'hello']
####方法二
list1 = ['abc',1,2,'www']
list2 = ['python','hello']
list1.extend(list2)
print(list1)
# 返回 ['abc', 1, 2, 'www', 'python', 'hello']
2.删除
(1)del:根据索引位置删除
list1 = ['hello','world','abc','hello',1,2,'www']
del list1[3]
print(list1)
#返回 ['hello', 'world', 'abc', 1, 2, 'www']
(2)remove('xxxx'):删除指定元素(重复元素默认删除第一个)
list1 = ['hello','world','abc','hello',1,2,'www']
list1.remove('hello')
print(list1)
#返回 ['world', 'abc', 'hello', 1, 2, 'www']
(3)pop:按照索引删除
##默认删除最后一个元素
list1 = ['hello','world','abc','hello',1,2,'www']
list1.pop()
print(list1)
#返回 ['hello', 'world', 'abc', 'hello', 1, 2]
##按照索引删除
list1 = ['hello','world','abc','hello',1,2,'www']
list1.pop(3)
print(list1)
#返回 ['hello', 'world', 'abc', 1, 2, 'www']
(4)clear:清空列表
list1 = ['hello','world','abc','hello',1,2,'www']
list1.clear()
print(list1)
#返回 []
3.更新:按照索引更改
list1 = ['hello','world','www']
list1[2] = '123'
print(list1)
#返回 ['hello', 'world', '123']
(四)列表中的查找(列表中无find方法)
1.count:计数,返回某个元素在列表当中的个数
list1 = ['hello','world','abc','hello',1,2,'www']
print(list1.count('hello'))
#返回 2
2.index:查找,从左往右查找指定元素的索引位置,如果没有找到,报错
list1 = ['hello','world','abc','hello',1,2,'www']
print(list1.index('www'))
#返回 6
3.in(not in)成员运算:查找元素是否在列表中,如果是输出true,否则false
list1 = ['hello','world','abc','hello',1,2,'www']
'www' in list1
#返回 True
(五)列表的排序
1.reverse:倒序
list1 = ['hello','world','123']
list1.reverse()
print(list1)
#返回 ['123', 'world', 'hello']
2.sort:按照ascii码表书序进行排序
###正序
list1 = ['hello','world','123']
list1.sort() #不写默认正序 (reverse=False)
print(list1)
#返回 ['123', 'hello', 'world']
###倒序
list1 = ['hello','world','123']
list1.sort(reverse=True)
print(list1)
#返回 ['world', 'hello', '123']
