列表:
列表的创建
lst = [‘hello’,‘python’,98]
lst2 = list([‘hello’,‘python’,98])
列表的特点
lst = [‘hello’,‘python’,98,‘hello’]
lst2 = list([‘hello’,‘python’,98])
print(lst)
print(lst[0])
print(lst[-4])
print(lst[-1])
lst = [‘hello’, ‘python’, 98, ‘hello’]
print(lst)
print(lst.index(‘hello’))
#print(lst.index(‘java’)) #ValueError: ‘hello’ is not in list
print(lst.index(‘hello’, 1))
#print(lst.index(‘hello’,1,3)) #ValueError: ‘hello’ is not in list
print(lst.index(‘hello’, 1, 6))
获取列表中指定的元素
lst = [‘hello’, ‘python’, 98, ‘hello’,‘python’,67]
print(lst)
print(lst[1])
print(lst[-2])
#print(lst[100]) #IndexError: list index out of range
切片的操作
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(lst[0:10])
print(lst[0:10:2])
print(lst[:7])
print(lst[::])
print(lst[::2])
print(lst[-1])
print(lst[-11:-5])
print(lst[::-1])
列表的判断及遍历
s = ‘hello world’
lst = [‘hello’, ‘world’, ‘java’, ‘python’, ‘2222’]
print(‘l’ in s)
print(‘hello’ in lst)
print(‘java’ not in lst)
for item in lst:
print(item)
列表的增删改查操作
lst = [‘hello’, ‘world’, ‘java’, ‘python’, ‘2222’]
lst.append(‘javascript1’)
print(lst)
lst.extend([‘小明’, 77, 23.23, True])
print(lst)
lst.extend({‘小明’, 77, 23.23, True})
print(lst)
lst.insert(1,‘大疆无人机’)
print(lst)
lst2 = lst[:5:1]
lst[1:] = lst2
print(lst)
列表元素的删除操作
lst = [‘hello’, ‘world’, ‘java’, ‘python’, ‘2222’,‘hello’,‘haha’]
lst.remove(‘hello’)
print(‘remove’, lst)
#lst.remove(‘hel’) #ValueError: list.remove(x): x not in list
lst.pop(1)
print(‘pop’, lst)
#lst.pop(22) #IndexError: pop index out of range
lst.pop()
print(‘pop 移除最后一位’, lst)
lst[1:2] = []
print(‘切片’, lst)
del lst[1]
print(‘del’, lst)
lst.clear()
print(‘clear’, lst)
del lst
#print(lst) #NameError: name ‘lst’ is not defined
lst = [‘hello’, ‘world’, ‘java’, ‘python’, ‘2222’,‘hello’,‘haha’]
lst[1] = ‘你好’
print(lst)
lst[1:6] = [‘python’,‘java’]
print(lst)
列表的排序操作
lst = [10, 15, 30, 50, 16, 7, 44]
lst.sort()
print(lst, id(lst))
lst.sort(reverse=True)
print(lst, id(lst))
#使用内置函数排序sorted 将产生一个新的列表对象
lst1 = sorted(lst)
print(lst1, id(lst), id(lst1))
lst2 = sorted(lst, reverse=True)
print(lst2, id(lst), id(lst2))
列表生成式:
列表有一定的规律
lst = [i for i in range(1, 6)]
print(lst)
本章总结: