Python 操作列表

1 遍历列表元素

colors = ["red","blue","yellow","orange","white","pink","brown"]
for color in colors :
    print(color)

 2 使用range()创建数值列表

# 使用range创建数值列表
numbers = list(range(1, 11))  # range不包括最后一个值
print(numbers)

# 指定步长,可创建基数或者偶数数值列表
numbers = list(range(2, 11, 2))
print(numbers)
numbers = list(range(1, 11, 2))
print(numbers)

# 使用**(乘方)创建乘方列表
squares = []
for value in range(1, 11):
    squares.append(value**2)
print(squares)

3 数值列表中最大值,最小值

squares = []
for value in range(1, 11):
    squares.append(value**2)
print(squares)
# 列表中最大值
print(max(squares))
# 列表中最小值
print(min(squares))

4 使用列表解析创建列表

squares = [value**2 for value in range(1, 11)]
print(squares)
# 说明:指定一个表达式(value**2),写一个for循环,用于给表达式提供值

5 使用列表的一部分(切片)

# 指定第一个元素索引和最后一个元素索引+1
colors = ["red", "blue", "yellow", "orange", "white", "pink", "brown"]
print(colors[1:4])

# 没有指定第一个索引,从列表开头开始
print(colors[:4])

# 没有指定最后索引,截止到列表最后一个元素
print(colors[4:])

# 截取列表后3个元素
print(colors[-5:])

# 遍历切片
for color in colors[-3:]:
    print(color)

6 复制列表

# 如果单纯的给一个变量赋值,并没有复制列表,两个变量指向同一个列表
colors = ["red", "blue", "yellow", "orange", "white", "pink", "brown"]
colors_copy = colors
colors_copy.append("green")
print(colors) # colors列表也发生变化了

# 使用切片复制列表
colors_copy = colors[:]
colors_copy.append("black")
print(colors)
print(colors_copy)

7 不可变列表(元组)

# 定义元组,使用圆括号而不是方括号
colors = ("red", "blue", "yellow", "orange", "white", "pink", "brown")
print(colors[1])

# 如果修改元组中的元素,将返回类型错误信息
colors[0] = "black"
# 错误信息:TypeError: 'tuple' object does not support item assignment

# 但可以给元组变量重新赋值,达到修改元组的目的
colors = ("red", "blue")
print(colors)