Python学习之路(3)列表简介

茴香豆 Lv5

本章和下一章,将学习列表是什么以及如何使用列表元素。列表让你能够在一个地方存储成组的信息。

认识列表

列表由一系列按特定顺序排列的元素组成。鉴于列表通常包含多个元素,给列表指定一个表示复数的名称是个不错的主意。

Python中,用 [ ] 来表示列表,用逗号分隔其中的元素。示例:

1
2
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles) # ['trek', 'cannondale', 'redline', 'specialized']

1.访问列表元素

1
2
3
4
5
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# access list element 访问第n个元素(从0开始)
print(bicycles[0]) # trek
# access the n element from bottom of the list 访问倒数第n个元素(从-1开始)
print(bicycles[-1]) # specialized

2.修改、添加和删除元素

修改元素:

1
2
3
4
5
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles) # ['honda', 'yamaha', 'suzuki']
# change element 修改元素
motorcycles[0] = 'ducati'
print(motorcycles) # ['ducati', 'yamaha', 'suzuki']

添加元素:

1
2
3
4
5
6
# add element at the end 在末尾添加元素
motorcycles.append('honda')
print(motorcycles) # ['ducati', 'yamaha', 'suzuki', 'honda']
# insert element 在指定位置添加元素
motorcycles.insert(0,'ducatipro')
print(motorcycles) # ['ducatipro', 'ducati', 'yamaha', 'suzuki', 'honda']

删除元素:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# delete element 删除指定位置元素
del motorcycles[0]
print(motorcycles) # ['ducati', 'yamaha', 'suzuki', 'honda']
# pop element 获取指定位置元素并在列表中删除(默认删除表尾元素)
poped_motorcycle = motorcycles.pop()
print(motorcycles) # ['ducati', 'yamaha', 'suzuki']
print(poped_motorcycle) # honda
poped_motorcycle = motorcycles.pop(0)
print(motorcycles) # ['yamaha', 'suzuki']
print(poped_motorcycle) # ducati
# delete accroding value 根据值删除元素
# notice: remove only delete the first same element 注意:remove只删除第一个相同的元素
too_expensive = 'yamaha'
motorcycles.remove(too_expensive)
print(motorcycles) # ['suzuki']
print(too_expensive) # yamaga

3.组织列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cars = ['bmw', 'audi', 'toyota', 'subaru']
# forever sort list 永久排序
cars.sort()
print(cars) # ['audi', 'bmw', 'subaru', 'toyota']
# reverse sort list 逆序排序
cars.sort(reverse=True)
print(cars) # ['toyota', 'subaru', 'bmw', 'audi']
# temporary sort list(reverse same) 临时排序(逆序同样适用)
print(cars) # ['toyota', 'subaru', 'bmw', 'audi']
print(sorted(cars)) # ['audi', 'bmw', 'subaru', 'toyota']
# reverse list 列表反转
cars.reverse()
print(cars) # ['audi', 'bmw', 'subaru', 'toyota']
# get list's length
print(len(cars)) # 4
  • Title: Python学习之路(3)列表简介
  • Author: 茴香豆
  • Created at : 2022-06-30 22:53:35
  • Updated at : 2022-07-01 11:33:20
  • Link: https://hxiangdou.github.io/2022/06/30/Python_3/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Python学习之路(3)列表简介