Python列表常用操作

Python的列表非常好用,一些常用的操作寫在這裏。


在Python中創建一個列表時,解釋器會在內存中創建一個類似數組(但不是數組)的數據結構來存儲數據。列表中的編號從 0 開始,然後是1,依此類推。

這裏寫圖片描述



print() 顯示列表;

len() 得出列表中有多少數據項;

append() 在列表末尾追加一個數據項;

extend() 在列表末尾增加一個數據項集合;

pop() 在列表末尾刪除一個數據項;

remove() 在列表中刪除一個特定的數據項;

insert() 在特定位置前面增加一個數據項;

count() 統計某個數據項在列表中出現的次數;

reverse() 反向列表中數據項。


>>> Fruit = ["Apple","Pear","Grape","Peach","Bananer"]
>>> print(len(Fruit))
5
>>> print(Fruit[0])
Apple
>>> print(Fruit[4])
Bananer

>>> Fruit.append("tomato")
>>> print(Fruit)
['Apple', 'Pear', 'Grape', 'Peach', 'Bananer', 'tomato']

>>> Fruit.extend(["lemon","coconut"])
>>> print(Fruit)
['Apple', 'Pear', 'Grape', 'Peach', 'Bananer', 'tomato', 'lemon', 'coconut']

>>> Fruit.pop()
'coconut'
>>> print(Fruit)
['Apple', 'Pear', 'Grape', 'Peach', 'Bananer', 'tomato', 'lemon']

>>> Fruit.remove("Peach")
>>> print(Fruit)
['Apple', 'Pear', 'Grape', 'Bananer', 'tomato', 'lemon']
>>> Fruit.remove(Fruit[0])
>>> print(Fruit)
['Pear', 'Grape', 'Bananer', 'tomato', 'lemon']

>>> Fruit.insert(0,"Apple")
>>> print(Fruit)
['Apple', 'Pear', 'Grape', 'Bananer', 'tomato', 'lemon']
>>> Fruit.insert(6,"coconut")
>>> print(Fruit)
['Apple', 'Pear', 'Grape', 'Bananer', 'tomato', 'lemon', 'coconut']

>>> Fruit.count("Apple")
1





用迭代顯示列表中的數據項,以下的代碼段中 forwhile 完成的工作是一樣的:

>>> for item in Fruit:
    print(item)
>>> while count < len(Fruit):
      print(Fruit[count]) 
      count = count + 1
# 輸出結果
Apple
1
Pear
2
Bananer
3


如果字符串中需要包含雙引號,不要忘記轉義 ,\”

>>> Fruit.append("\"Tomato\"")
>>> print(Fruit)
['Apple', 1, 'Pear', 2, 'Bananer', 3, '"Tomato"']


isinstance() 函數可以用來判斷特定標識符是否包含某個特定類型的數據。

>>> isinstance(Fruit,list)
True

>>> isinstance(count,list)
False



Python中列表可以嵌套,並且可以支持任意多層的嵌套,例如:

>>> print(Fruit)
['Apple', 1, 'Pear', 2, 'Bananer', 3]

>>> Fruit.append(["A","B","C"])
>>> print(Fruit)
['Apple', 1, 'Pear', 2, 'Bananer', 3, '"Tomato"', ['A', 'B', 'C']]

>>> Fruit[-1].append(["aa","bb","cc"])
>>> print(Fruit)
['Apple', 1, 'Pear', 2, 'Bananer', 3, '"Tomato"', ['A', 'B', 'C', ['aa', 'bb', 'cc']]]
>>> for i in Fruit:
    print(i)

Apple
1
Pear
2
Bananer
3
"Tomato"
['A', 'B', 'C', ['aa', 'bb', 'cc']]

試試輸出三層嵌套的列表中的各個數據項:

>>> for i in Fruit:
    if isinstance(i,list):
        for j in i:
            if isinstance(j,list):
                for k in j:
                    print(k)
            else:
                print(j)
    else:
        print(i)


Apple
1
Pear
2
Bananer
3
"Tomato"
A
B
C
aa
bb
cc



上面的循環嵌入的有點多,如果是N層嵌套的列表重複代碼會很多,來點優化試試:

>>> def my_print(mylist):
    for i in mylist:
        if isinstance(i,list):
            my_print(i)
        else:
            print(i)

>>> my_print(Fruit)

Apple
1
Pear
2
Bananer
3
"Tomato"
A
B
C
aa
bb
cc

定義個遞歸函數實現,看起來好多了。



列表操作符部分,+表示列表組合,*表示列表重複:

>>> mylist = [1,2,3] + [4,5,6]
>>> print mylist
[1, 2, 3, 4, 5, 6]

>>> mylist = mylist*4
>>> print(mylist)
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]


今天就寫到這裏吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章