列表是什么
name = ["jim", "lilei", "lucy"] #方括号表示,逗号分隔 print(name) print(name[0]) print(name[0].title())
输出:
['jim', 'lilei', 'lucy']
jim
Jim
name = ["jim", "lilei", "lucy"] print(name[0], name[1], name[2]) print(name[-1], name[-2], name[-3]) #-1索引表示最后一个元素
输出:
jim lilei lucy
lucy lilei jim
name = ["jim", "lilei", "lucy"] name[0] = 'lily' #修改第一个元素 print(name) #添加元素 name.append('xiaoming') #在末尾添加 print(name) name.insert(1,'ouyangfeng') #在name[1]处添加,原来的name[1]以及以后的后移 print(name) del name[1] #删除name[1],以后不用name[1]了 print(name) delete_end = name.pop() print(delete_end, name) delete_name = name.pop(1) #删除name[1],以后还可以用 print("delete_name: ",delete_name) print(name) name.remove('lucy') #删除lucy print(name)
输出:
['lily', 'lilei', 'lucy']
['lily', 'lilei', 'lucy', 'xiaoming']
['lily', 'ouyangfeng', 'lilei', 'lucy', 'xiaoming']
['lily', 'lilei', 'lucy', 'xiaoming']
xiaoming ['lily', 'lilei', 'lucy']
delete_name: lilei
['lily', 'lucy']
['lily']
永久排序:
cars =['dazhong','Baoma','aodi','qq','Qirui'] cars.sort() #按字母从小到大 print(cars) cars.sort(reverse=True) #按字母从大到小 print(cars)
output:
['Baoma', 'Qirui', 'aodi', 'dazhong', 'qq']
['qq', 'dazhong', 'aodi', 'Qirui', 'Baoma']
临时排序:
cars =['dazhong','Baoma','aodi','qq','Qirui'] tmp_sort = sorted(cars) print("tmp_sort:",tmp_sort) print("origianl:",cars) print("large->small:",sorted(cars,reverse=True)) print("origianl:",cars)
output:
tmp_sort: ['Baoma', 'Qirui', 'aodi', 'dazhong', 'qq']
origianl: ['dazhong', 'Baoma', 'aodi', 'qq', 'Qirui']
large->small: ['qq', 'dazhong', 'aodi', 'Qirui', 'Baoma']
origianl: ['dazhong', 'Baoma', 'aodi', 'qq', 'Qirui']
反转:
cars =['dazhong','Baoma','aodi','qq','Qirui'] print(cars) cars.reverse() print(cars) cars.reverse() print("recover: ", cars)
output:
['dazhong', 'Baoma', 'aodi', 'qq', 'Qirui']
['Qirui', 'qq', 'aodi', 'Baoma', 'dazhong']
recover: ['dazhong', 'Baoma', 'aodi', 'qq', 'Qirui']
cars =['dazhong','Baoma','aodi','qq','Qirui'] length = len(cars) print(length)
output:
5