1. 程式人生 > >python3 列表、元組操作

python3 列表、元組操作

python3 列表、函數基礎操作

>> alist = [1,2,3,4,5,6,7,8,9]
>> alist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>> alist. #兩次TAB鍵

alist.append(    #添加

alist.count(9)      #統計單個字符出現的次數

alist.insert(   #插入在指定位置插入參數   
        >>> alist.insert(3,4)
        >>> alist
        [1, 2, 3, 4]

alist.reverse() #倒序打印

alist.clear(   

alist.extend(‘new‘)       #把new當成三個字符,進行添加
        >>> alist.extend(‘new‘)
        >>> alist
        [1, 2, 3, 4, 5, 6, 7, 8, 9, ‘n‘, ‘e‘, ‘w‘]
        >>> alist.extend([‘hello‘,‘world‘])
        >>> alist
        [1, 2, 3, 4, 5, 6, 7, 8, 9, ‘n‘, ‘e‘, ‘w‘, ‘hello‘, ‘world‘]

alist.pop(        #刪除,並彈出

alist.sort()    #升序排序,改變列表本身
    >>> alist = [3,5,2,6,2]
    >>> alist.sort()
    >>> alist
    [2, 2, 3, 5, 6]

alist.copy(    

alist.index(6)   #返回參數的下標,一個參數出現多次返回第一個參數的下標
    >>> alist.index(6)
        5

alist.remove(   

shuffle    #打亂列表順序
    >>> from random import shuffle
    >>> alist
    [97, 97, 97, 94, 79, 70, 57, 16, 11, 9]
    >>> shuffle(alist)
    >>> alist
    [79, 16, 97, 94, 97, 11, 97, 70, 9, 57]

join:
    >>> str_list = [‘h‘,‘e‘,‘l‘,‘l‘,‘o‘]
    >>> str_list
    [‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘]
    >>> ‘‘.join(str_list)         #將列表轉換成字符串,以空為鏈接符
    ‘hello‘
    >>> ‘.‘.join(str_list)        #以.為鏈接符,轉換列表為字符串
    ‘h.e.l.l.o‘

元組:
atuple = (1, [], 3)

>> atuple = (1, [], 3)
>> atuple
(1, [], 3)
>> atuple[1]
[]>>> atuple[1].append(2)
>> atuple
(1, [2], 3)
>> atuple[1].append(3)
>> atuple
(1, [2, 3], 3)

python3 列表、元組操作