Python学习之路3-操作列表

《Python编程：从入门到实践》笔记。

1. 遍历列表

# 代码：
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick")
print("I can't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was a great magic show!")

# 输出：
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

David, that was a great trick!
I can't wait to see your next trick, David.

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!

2. 创建数值列表

# 代码：
print(list(range(6)))         # 结束值（不包含结束值）
print(list(range(1, 6)))      # 起始值（包含），结束值（不含）
print(list(range(1, 6, 2)))   # 起始值，结束值，步长；最后一个数小于结束值
print(list(range(6, 1, -1)))  # 负数步长，此时起始值要大于结束值
print(list(range(1, 6, -1)))  # 负数步长，若起始值小于结束值，则输出空列表

# 结果：
[0, 1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 3, 5]
[6, 5, 4, 3, 2]
[]

range()函数也常用语for循环，用于标识循环次数，或者用于生成更复杂的列表：

# 代码：
squares = []
for value in range(1, 11):
squares.append(value ** 2 + 1)
print(squares)

# 结果：
[2, 5, 10, 17, 26, 37, 50, 65, 82, 101]

# 代码：
squares = [value ** 2 for value in range(1, 11)]
print(squares)

squares_2 = [value ** 2 for value in range(1, 11) if value % 2 == 0]
print(squares_2)
# 结果：
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[4, 16, 36, 64, 100]

# 代码：
digits = list(range(10))
print(min(digits), max(digits), sum(digits))

# 结果：
0 9 45

3. 使用列表的一部分

3.1 切片

# 代码：
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# [起始：结束：步长]， 其中，结果列表包含起始索引，但不包含结束索引
print(players[0:3])
print(players[:3])   # 如果从0开始切片，0可以省略
print(players[1:3])
print(players[2:])   # 如果要便利到最后一个元素，结束索引可以省略，此时最后一个元素会被包含
print(players[-3:])
print(players[::2])  # 设置了步长，但省略了结束索引，列表最后一个元素如果被遍历到，则会被包含
print(players[:4:2]) # 设置了步长和结束索引，索引4的元素也被遍历到了，但不会被包含在结果中

# 结果：
['charles', 'martina', 'michael']
['charles', 'martina', 'michael']
['martina', 'michael']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'michael', 'eli']
['charles', 'michael']

3.2 复制列表

# 代码：
# 浅复制
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players)

names = players
names.append("test")
print(players)

# 结果：
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'test']

# 代码：
# 深复制
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players)

names = players[:]
names.append("test")
print(names)
print(players)

# 结果：
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'test']
['charles', 'martina', 'michael', 'florence', 'eli']

4. 元组（tuple）

# 代码：
my_tuple = ()    # 空元组
one_tuple = (1,) # 声明含有一个元素的元组。不是one_tuple = (1)

# 代码：
test_tuple = (1, 2, 3, 4, 5)
print(test_tuple)
test_tuple = (2, 3, 4, 5, 6)
print(test_tuple)

# 结果：
(1, 2, 3, 4, 5)
(2, 3, 4, 5, 6)