列表基本使用
name_list = ["zhangsan", "lisi", "wangwu"]# 1. 取值和取索引
# list index out of range - 列表索引超出范圍
print(name_list[2])# 知道數據的內容,想確定數據在列表中的位置
# 使用index方法需要注意,如果傳遞的數據不在列表中,程序會報錯!
print(name_list.index("wangwu"))# 2. 修改
name_list[1] = "李四"
# list assignment index out of range
# 列表指定的索引超出范圍,程序會報錯!
# name_list[3] = "王小二"# 3. 增加
# append 方法可以向列表的末尾追加數據
name_list.append("王小二")
# insert 方法可以在列表的指定索引位置插入數據
name_list.insert(1, "小美眉")# extend 方法可以把其他列表中的完整內容,追加到當前列表的末尾
temp_list = ["孫悟空", "豬二哥", "沙師弟"]
name_list.extend(temp_list)# 4. 刪除
# remove 方法可以從列表中刪除指定的數據
name_list.remove("wangwu")
# pop 方法默認可以把列表中最后一個元素刪除
name_list.pop()
# pop 方法可以指定要刪除元素的索引
name_list.pop(3)
# clear 方法可以清空列表
name_list.clear()print(name_list)
?
總結
- 上一篇: 模块-使用模块演练
- 下一篇: 列表-使用del关键字从列表删除数据