Python基础(二)-列表

Python列表

访问列表元素

1
2
3
4
5
6
7
8
9
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0])

输出结果:trek

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

输出结果:specialized
  • 通过元素索引即可访问列表数据
  • 索引从0开始,-1表示最后一个元素,-2表示倒数第二个元素,以此类推

使用列表中的各个值

1
2
3
4
5
bicycles = ['trek','cannondale','redline','specialized']
message = "My first bicycles was a " + bicycles[0].title() + "."
print(message)

输出结果:My first bicycles was a Trek .
  • 字符串拼接通过 + 号连接
  • title() 函数可以将字符串首字母变大写

修改列表元素

1
2
3
4
5
6
bicycles = ['trek','cannondale','redline','specialized']
# 修改第一个元素为 fenghuangpai
bicycles[0] = 'fenghuangpai'
print(bicycles)

输出结果:['fenghuangpai','cannondale','redline','specialized']
  • #是注释的开始
  • 通过索引找到元素,然后赋新的值给该索引对应的元素即可修改

添加列表元素

1
2
3
4
5
6
7
8
9
10
11
12
13
bicycles = ['trek','cannondale','redline','specialized']
# 在列表末尾添加 fenghuangpai 元素
bicycles.append('fenghuangpai')
print(bicycles)

输出结果:['trek','cannondale','redline','specialized','fenghuangpai']

bicycles = ['trek','cannondale','redline','specialized']
# 在列表中添加 fenghuangpai 元素
bicycles.insert(1,'fenghuangpai')
print(bicycles)

输出结果:['trek','fenghuangpai','cannondale','redline','specialized']
  • append() 函数在列表末尾添加元素
  • insert() 函数可以通过索引去指定位置添加元素,注意数组越界

删除列表元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 使用 del 语句删除元素
bicycles = ['trek','cannondale','redline','specialized']
del bicycles[0]
print(bicycles)

输出结果:['cannondale','redline','specialized']

# 使用pop()删除元素
bicycles = ['trek','cannondale','redline','specialized']
poped_bicycles = bicycles.pop()
print(poped_bicycles)

输出结果:['trek','cannondale','redline']

# 弹出列表中任意位置的元素
bicycles = ['trek','cannondale','redline','specialized']
poped_bicycles = bicycles.pop(1)
print(poped_bicycles)

输出结果:['trek','redline','specialized']

# 根据值删除元素
bicycles = ['trek','cannondale','redline','specialized']
poped_bicycles = bicycles.remove('redline')
print(poped_bicycles)

输出结果:['trek','cannondale','specialized']
  • pop() 和 del 的区别

如果要从列表中删除一个元素且不再以任何方式使用它,就用del语句,如果你在删除元素后还要继续使用它,就使用pop()

列表排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 字母正序
bicycles = ['trek','cannondale','redline','specialized']
bicycles.sort()
print(bicycles)

输出结果:['cannondale','redline',specialized','trek']

# 字母反序
bicycles = ['trek','cannondale','redline','specialized']
bicycles.sort(reverse=True)
print(bicycles)

输出结果:['trek','specialized','redline','cannondale']

# 倒着打印
bicycles = ['trek','cannondale','redline','specialized']
bicycles.reverse()
print(bicycles)

输出结果:['specialized','redline','cannondale','trek']

获取列表长度

1
2
3
4
bicycles = ['trek','cannondale','redline','specialized']
len(bicycles)

输出结果:4
小额支持我写出更好的文章~