Python入門(六) list

來源:互聯網
上載者:User

標籤:

    Python中的list,跟c++中的vertor有些類似,支援隨機訪問,可以動態增加或者刪除資料,但是list要比vector更加靈活,可以存放任意類型的元素,包括嵌套list。

    1. list的建立: 使用[]表示,元素之間用括弧分割。

list1 = [‘a‘, ‘b‘, ‘c‘]

    2. 訪問list中的元素:

#通過下標遍曆listfor i in range(len(list1)):    print list1[i]    #通過for迭代listfor v in list1:    print(v)

    list中的元素,直接通過下標訪問,跟c語言的數組很像,下標也是從0開始。

#修改list中的元素list1[0] = ‘ab‘print(list1)>>> [‘ab‘, ‘b‘, ‘c‘]

    刪除list中的某個元素:

del list1[1]print(list1)>>> [‘ab‘, ‘c‘]

    list是可以動態增加與刪除元素的,增加就不像刪除這麼簡單了,如:

#像list尾部插入一個元素list1[len(list1)] = ‘d‘Traceback (most recent call last):  File "<pyshell#19>", line 1, in <module>    list1[len(list1)] = ‘d‘IndexError: list assignment index out of range

    說明插入一個元素不能夠直接操作,要通過insert或者是append方法來完成:

#從尾部插入list1.append(‘d‘)print(list1)>>> [‘ab‘, ‘c‘, ‘d‘]#在指定位置插入list1.insert(1, ‘e‘)print(list1)>>> [‘ab‘, ‘e‘, ‘c‘, ‘d‘]list1.insert(100, ‘x‘)print(list1)>>> [‘ab‘, ‘e‘, ‘c‘, ‘d‘, ‘x‘]

    從上面的結果來看,insert方法在指定位置插入時,如果指定位置已經有元素了,那麼會將此元素及其後面的元素進行移動。如果指定的位置超出了末尾的位置,則會將元素插入到尾部。

    3. 截取list中的部分元素: 這個與tuple一樣, [left : right, step], 左邊閉合,右邊開放

print(list1[1:3])>>> [‘e‘, ‘c‘]print(list1[1:-1])>>> [‘e‘, ‘c‘, ‘d‘]

    4. list中其他常用的方法:

1)reverse() : 反轉list

list1.reverse()print(list1)>>> [‘x‘, ‘d‘, ‘c‘, ‘e‘, ‘ab‘]

2)remove(value) : 移除list中第一個值匹配value的元素

list1.remove(‘ab‘)print(list1)>>> [‘x‘, ‘d‘, ‘c‘, ‘e‘]

3) pop() : 移除list中最後一個元素,並將其返回

printf(list1.pop())>>> ‘e‘print(list1)>>> [‘x‘, ‘d‘, ‘c‘]

4) count(value) : 通過list中值等於value的元素個數

list1.count(‘a‘)>>> 0list1.count(‘x‘)>>> 1

5) sort(func) : 對list的元素進行排序

list1.sort()print(list1)>>> [‘c‘, ‘d‘, ‘x‘]

6)index(value) : 尋找第一個匹配value的元素,返回其索引值

list1.index(‘d‘)>>> 1

    如果只是簡單的判斷某個元素是否存在於list中,可以直接使用in進行判斷

if ‘d‘ in list1:    print(‘d is in list1‘)else:    print(‘d is not in list1‘)   >>> d is in list1


Python入門(六) list

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.