python基礎-list

來源:互聯網
上載者:User
1、list建立

new_list1 = ['TV','Car','Cloth','Food']
new_list2 = list(['TV','Car','Cloth','Food'])
print (new_list1)
print (new_list2)
運行結果:
['TV', 'Car', 'Cloth', 'Food']
['TV', 'Car', 'Cloth', 'Food']

2、list常用的方法:

1. append

new_list1 = ['TV','Car','Cloth','Food']
print (new_list1)
new_list1.append('Water') #追加'water'
print (new_list1)
運行結果:
['TV', 'Car', 'Cloth', 'Food']
['TV', 'Car', 'Cloth', 'Food', 'Water']

2.count

new_list1 = ['TV','Car','Cloth','Food','Food']
print (new_list1.count('Food')) #統計'food'在列表中的次數 => 2次

3.extend

new_list1 = ['TV','Car','Cloth','Food','Food']
new_list1.extend([11,22,33,'Car'])
print (new_list1)
運行結果:
['TV', 'Car', 'Cloth', 'Food', 'Food', 11, 22, 33, 'Car']

4.sort

new_list1 = ['TV','Car','Cloth','Food','Food']
print (new_list1)
new_list1.sort()#正向排序
print (new_list1)
new_list1.sort(reverse=True)#反向排序
print (new_list1)
運行結果:
['TV', 'Car', 'Cloth', 'Food', 'Food']
['Car', 'Cloth', 'Food', 'Food', 'TV']#正向排序結果
['TV', 'Food', 'Food', 'Cloth', 'Car']#反向排序結果

5. len

new_list1 = ['TV','Car','Food','Cloth','Food']
print (len(new_list1)) => 5 #列印元素的個數

6.remove

new_list1 = ['TV','Car','Food','Cloth','Food']

new_list1.remove('Food')
print (new_list1)
運行結果:
['TV', 'Car', 'Cloth', 'Food'] #remove會刪除找到的第一個相同元素

7.pop

new_list1 = ['TV','Car','Food','Cloth','Food']
new_list1.pop()#隨機刪除一個元素
print (new_list1)
new_list1.pop(2)#指定刪除某個元素
print (new_list1)
運行結果為:
['TV', 'Car', 'Food', 'Cloth']
['TV', 'Car', 'Cloth']#,此處刪除的是第3個元素'Food'

8.index

new_list1 = ['TV','Car','Food','Cloth','Food']
print (new_list1.index('Food'))#返回指定元素的index值,相同元素返回尋找到的第一個
運行結果為:2

9.insert

new_list1 = ['TV','Car','Food','Cloth','Food']
new_list1.insert(2,'HAHAHA') #向指定的位置插入元素
print (new_list1)
運行結果為:
['TV', 'Car', 'HAHAHA', 'Food', 'Cloth', 'Food']

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.