1. 程式人生 > >python列表及其操作

python列表及其操作

# -*-coding:utf-8-*-
# !/usr/bin/env python
# Author:@vilicute

# 列表初始化
myList = [x for x in range(10) if not x % 2] # myList = [0, 2, 4, 6, 8]

myList1 = ["aaa", "bbb", "ccc", "ddd", "eee", "fff"]

myList2 = ["ggg", "hhh", "iii", "jjj"]

# 列表操作

print(myList[2], myList[-2], myList1[:3], myList1[-3:-1], myList1[1:4])

myList1.insert
(1, "liangba") # 插入指定位置

myList1.append("xxx") # 在末尾新增

myList1.remove("xxx") # 直接刪除某個內容

del myList1[1] # 通過下標進行刪除

myList1.pop() # 預設無下標時刪除最後一個,有則刪除制定位置,例如:myList1.pop(1)

myList1.count(myList1[2]) # 統計相同項個數

myList1.reverse() # 反轉

xx = myList1.index("ccc") # 位置查詢

myList1.sort() # 按字母順序排序

myList1.extend
(myList2) # 列表合併

del myList2 # 刪除 myList2