python學習list筆記

來源:互聯網
上載者:User

標籤:python學習list筆記

python學習list筆記

List(列表) 是 Python 中使用最頻繁的資料類型;

支援字元,數字,字串甚至可以包含列表(所謂嵌套)

1、定義:

list = [1,3,4,5,‘goog‘,‘well‘,777]

2、從最後一列增加:

 list.append("your are good!")

顯示:

直接輸入:list

顯示:[1, 3, 4, 5, ‘goog‘, ‘well‘, 777, ‘your are good!‘]

3、從中間增加一列如:

使用:insert函數:

使用方法如下:

>>> list.insert(8,‘liwen‘)

>>> list

[1, 3, 4, 5, ‘goog‘, ‘liwen‘, ‘well‘, ‘liwen‘, ‘liwen‘, 777, ‘your are good!‘]

4、刪除一個:

使用del

如:

>>> list

[1, 3, 4, 5, ‘goog‘, ‘liwen‘, ‘well‘, ‘liwen‘, ‘liwen‘, 777, ‘your are good!‘]

>>> del list[1]  #刪除下標為第一個的值

>>> list

[1, 4, 5, ‘goog‘, ‘liwen‘, ‘well‘, ‘liwen‘, ‘liwen‘, 777, ‘your are good!‘]


5、遍曆全部值:

list = [1, 4, 5, ‘goog‘, ‘liwen‘, ‘well‘, ‘liwen‘, ‘liwen‘, 777, ‘your are good!‘]

使用for迴圈遍曆:

for i in list:

    print i


6、查看list長度使用len函數


list = [1, 4, 5, ‘goog‘, ‘liwen‘, ‘well‘, ‘liwen‘, ‘liwen‘, 777, ‘your are good!‘]

print len(list)

print ‘=====================‘


a = ‘ddddddddddddddddddd‘

print len(a)


10

=====================

19

=====================



7、計算:統計5出現了幾次:


c = [1,3,4,5,5,5,5,5,4,5,4,6,9]

ncount = 0

for i in c:

    if i == 5:

        ncount = ncount + 1

print ncount


結果:

6

==========ncount===========

偶數與奇數:

 range(1,101,2) 奇數

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23,25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63,65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

 range(2,101,2) 偶數

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66,68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]


補充:

1、

#!/usr/bin/env python

# -*- coding: utf-8 -*-

if __name__ == ‘__main__‘:

    list = [‘html‘, ‘js‘, ‘css‘, ‘python‘]


    # 方法1

    print u‘遍曆列表方法1:‘

    for i in list:

        print (u"序號:%s   值:%s" % (list.index(i) + 1, i))


    print u‘\n遍曆列表方法2:‘

    # 方法2

    for i in range(len(list)):

        print (u"序號:%s   值:%s" % (i + 1, list[i]))


    # 方法3

    print u‘\n遍曆列表方法3:‘

    for i, val in enumerate(list):

        print (u"序號:%s   值:%s" % (i + 1, val))


    # 方法3

    print u‘\n遍曆列表方法3 (設定遍曆開始初始位置,只改變了起始序號):‘

    for i, val in enumerate(list, 2):

        print (u"序號:%s   值:%s" % (i + 1, val))




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.