Python更新列表

Python更新列表:

使用索引下标进行更新:

# 修改列表的第 6 个元素为 d
lst = ['a','b','c',1,2,3]
lst[5] = 'd'
print(lst)
# ['a', 'b', 'c', 1, 2, 'd']

使用切片对列表进行更新:

# 修改列表的第2个元素到最后为 hey
lst = ['a','b','c',1,2]
lst[2:] = 'hey'
print(lst)
# ['a', 'b', 'h', 'e', 'y']

# 修改列表的第3个元素到第8个元素为 hello
lst = [1,2,3,'a','b','c','d','e',4,5,6]
lst[3:8] = 'hello'
print(lst)
# [1, 2, 3, 'h', 'e', 'l', 'l', 'o', 4, 5, 6]

使用 append 方法增加元素:

# 使用 append 方法对列表进行更新
lst = ['a','b','c',1,2,3]
lst.append('d')
print(lst)
# ['a', 'b', 'c', 1, 2, 3, 'd']

2020-02-09

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12286660.html