1、定义:
由一系列按特定顺序排列的元素组成,在Python中,用方括号([ ])来表示列表,并用逗号来分隔其中的元素。
2、访问列表元素:
可以指出列表元素的名称,在指出元素的索引,并将其放在方括号内。
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[2])
redline
当请求获取列表元素时,python只返回该元素,而不包括方括号和引号
- 可以使用字符串方法
- 元素索引从0而不是1开始,负号按逆序返回;
3、修改、添加和删除列表元素
-
修改:指定列表名和要修改的元素的索引,再指定该元素的新值。
motorcycles = ['honda','yamaha','suzuki'] print(motorcycles) motorcycles[2] = 'ducati' print(motorcycles)
-
添加元素:
-
将元素添加到列表末尾:
motorcycles = ['honda','yamaha','suzuki'] motorcycles.append('ducati') print(motorcycles)
方法append()将元素’ducati’添加到了列表末尾
-
在列表中插入元素:
motorcycles = ['honda','yamaha','suzuki'] motorcycles.insert(0,'ducati') print(motorcycles)
方法 insert( ),可在列表的任何位置添加新元素
-
-
删除元素:
-
使用del语句删除元素:
motorcycles = ['honda','yamaha','suzuki'] #删除列表的第二个元素 del motorcycles[1] print(motorcycles)
-
使用方法**pop()**删除元素:
方法pop()可删除列表末尾的元素,并让你能够接着使用它。
motorcycles = ['honda','yamaha','suzuki'] print(motorcycles) popped_motorcycle = motorcycles.pop() print(motorcycles) print(popped_motorcycle) ['honda','yamaha','suzuki'] ['honda','yamaha'] suzuki
使用pop( ),可以删除表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
-
根据值删除元素:【使用方法remove( )】
motorcycles = ['honda','yamaha','suzuki','ducati'] print(motorcycles) motorcycles.remove('ducati') print(motorcycles)
使用 remove ( ) 从列表删除元素时,也可以接着使用它的值。
注意:方法remove()只删除第一个指定的值,如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
-
4、组织列表:
-
使用**方法sort()**对列表进行永久性排序。
cars = ['bmw','audi','toyota','subaru'] #按字母顺序排序 cars.sort() #按与字母顺序相反的顺序排列列表元素 cars.sort(reverse = ture)
-
使用**函数sorted()**对列表进行临时排序。
cars = ['bmw','audi','toyota','subaru'] print("Here is the original list:") print(cars) print("Here is the sorted list:") print(sorted(cars)) #逆序排序 print(sorted(cars,reverse = True)
-
倒着打印列表:*要反转列表元素的排列顺序,可使用**方法 reverse()*永久性地修改列表元素的排列顺序。
cars = ['bmw','audi','toyota','subaru'] cars.reverse() print(cars)
-
确定列表的长度:
使用函数len()可快速获悉列表的长度
cars = ['bmw','audi','toyota','subaru'] len(cars) 4
-
避免索引超出列表长度。