1. 程式人生 > >python--列表list

python--列表list

python 列表list

********************* 列表list **********************

  1. 列表的定義

    定義一個空列表
    list = []
    定義一個包含元素的列表,元素可以是任意類型,包括數值類型,列表,字符串等均可。
    list = ["fentiao", 4, ‘gender‘]
    list1 = [‘fentiao‘,(4,‘male‘)]

    列表是可變類型的序列,而元組與字符串是不可變類型的序列
    # 此處定義一列表,名為list1
    >>> list1 = ["fentiao", 4, "male"]
    # 通過python的內置函數type查看list1的數據類型

    >>> type(list1)
    <type ‘list‘>

    # 此處我查看下標為1元素的值,重新給這個索引賦值,我們發現列表的元素是可變的;
    >>> list1[1]
    4
    >>> list1[1] = 5
    >>> list1
    [‘fentiao‘, 5, ‘male‘]
    列表的操作:理解"對象=屬性+方法"與類

    技術分享

    技術分享

  2. 列表的索引
    下標是從0開始計算,比如list[0]讀取的是列表的第1個元素;
    list[-1]讀取的是列表的倒數第1個元素;

    >>> list1[0]
    ‘fentiao‘
    >>> list1[-1]
    ‘male‘


  3. 列表判斷

    >>> list1

    [‘fentiao‘, 5, ‘male‘, ‘cat‘]

    1).查看列表長度:

    >>>len(list1)

    4

    2).列表元素的查找:

    >>>‘fentiao’ in list1

    True

    >>>‘fendai‘ in list1

    False

  4. 技術分享

  5. 列表的切片

    >>> list1[:] //通過切片的方式可以實現列表的復制
    [‘fentiao‘, 5, ‘male‘]

    0代表從哪個索引開始切片;
    3代表切片到哪個位置,並且不包含第三個索引;
    2代表切片的步長;
    >>> list1[0:3:2]
    [‘fentiao‘, ‘male‘]

    技術分享

  6. 列表的添加
    1).列表可通過append方法添加元素;添加到末尾
    >>> list1.append(‘cat‘)
    >>> list1
    [‘fentiao‘, 5, ‘male‘, ‘cat‘]

    >>>len(list1)

    4

    技術分享
    2).列表可通過方法添加元素;

    >>>list1.extend([‘hello‘,‘python‘])

    [‘fentiao‘, 5, ‘male‘, ‘cat‘,‘hello‘,‘python‘]

    技術分享
    3).在指定位置添加元素使用inert方法;
    L.insert(index, object) ##index指定位,object添加元素值

    技術分享

  7. 列表的修改
    修改列表的元素:直接重新賦值;

    >>>list1[0] = ‘fendai‘

    [‘fendai‘, 5, ‘male‘, ‘cat‘]

    技術分享

  8. 列表的查看
    查看某個列表元素的下表用index方法;

    >>>list1.index(‘fentiao‘) --‘fentiao‘在第0個元素位

    0

    >>>list1.append(‘fentiao‘)

    >>>list1.index(‘fentiao‘,1,5) --‘fentiao‘在第1到5之間的第4個元素位

    4
    查看某個列表元素出現的次數用count方法;

    技術分享



  1. 列表的刪除
    方法一:

list.remove(list[3]) ##刪除列表的元素

list.remove(‘male‘) ##刪除male

>>> list1.remove("cat")>>> list1
[‘fendai‘, 5, ‘male‘]


技術分享
方法二:

list.pop() ##默認刪除最後一位

list.pop(2) ##刪除第三個元素

技術分享

方法三:

del(list[3]) ##刪除列表元素

del list ##刪除列表

技術分享

練習

打印1-10中所有的偶數
打印1-10中所有的奇數

>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
>>> range(0,10,2)
[0, 2, 4, 6, 8]

技術分享

for語句:

技術分享

python--列表list