老齊python-基礎3(列表)

一、定義一個列表java

>>> a = []        #建立一個空列表
>>> type(a)      #查看數據類型
<class 'list'>   
>>> bool(a)      #判斷非空
False
>>> print(a)
[]
>>> a = ['2',3,'tajzhang',]
>>> a
['2', 3, 'tajzhang']
>>> type(a)
<class 'list'>
>>> bool(a)
True
>>> print(a)
['2', 3, 'tajzhang']

    列表是個筐,什麼都能裝python

>>> b = ["hello",a]
>>> b
['hello', ['2', 3, 'tajzhang']]

 

二、索引和切片linux

與字符串方式相同c++

>>> a = ['2','3','python.org']
>>> a[0]
'2'
>>> a[2]
'python.org'
>>> a[:2]
['2', '3']
>>> a[1:]
['3', 'python.org']
>>> a[2][7:13]  #兩次切片
'org'
>>> a.index('2') #索引
0
>>> a[-1]
'python.org'
>>> a[-3:-1] #從右向左截取
['2', '3']
>>> alst = [1,2,3,4,5,6]
>>> alst[:] #顯示列表全部
[1, 2, 3, 4, 5, 6]
>>> alst[::2] #步長爲2顯示列表
[1, 3, 5]
>>> alst[::1]
[1, 2, 3, 4, 5, 6]

 

三、反轉git

    編程中比較經常使用github

>>> alst = [1,2,3,4,5,6]
>>> alst[::-1]                  #反轉
[6, 5, 4, 3, 2, 1]
>>> alst
[1, 2, 3, 4, 5, 6]
>>> lang ='python'
>>> lang[::-1]          #字符串一樣支持反轉
'nohtyp'
>>> alst[::-2]   
[6, 4, 2]
>>> list(reversed(alst))    #反轉函數
[6, 5, 4, 3, 2, 1]
>>> list(reversed("abcd"))
['d', 'c', 'b', 'a']

四、操做列表shell

    4.1基本操做:與字符串操做方式基本相同編程

        lenubuntu

        +c#

        *

        in

        max()和min()

>>> lst = ['python','java','c++']
>>> len(lst)
3
>>> alst=[1,2,3,4,5,6]
>>> lst + alst
['python', 'java', 'c++', 1, 2, 3, 4, 5, 6]
>>> lst * 3
['python', 'java', 'c++', 'python', 'java', 'c++', 'python', 'java', 'c++']
>>> "python" in lst       #是否存在
True
>>> "c#" in lst      
False
>>> alst = [1,2,3,4,5,6]
>>> max(alst)       #最大值
6
>>> min(alst)       #最小值
1
>>> min(lst)
'c++'

    4.2修改列表元素

>>> cities = ["nanjing","zhejiang"]
>>> cities[1] = "suzhou"
>>> cities
['nanjing', 'suzhou']
>>> cities.append("shanghai")
>>> cities
['nanjing', 'suzhou', 'shanghai']
>>> cities[len(cities):] = ["wuxi"]
>>> cities
['nanjing', 'suzhou', 'shanghai', 'wuxi']

 

五、列表經常使用函數

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

    經常使用:append、count、extend、index、insert、pop、remove、reverse、sort

>>> la = [1,2,3]
>>> lb = ['tajzhang','python']
>>> la.extend(lb)             #列表合併
>>> la
[1, 2, 3, 'tajzhang', 'python']
>>> lb
['tajzhang', 'python']
>>> b = "abx"
>>> la.extend(b)              #將字符串加入列表
>>> la
[1, 2, 3, 'tajzhang', 'python', 'a', 'b', 'x']

>>> la = [1,2,3,'a','b','c']
>>> lb = ['qiwair','python']
>>> la[len(la):] = lb #不一樣實現方法
>>> la
[1, 2, 3, 'a', 'b', 'c', 'qiwair', 'python']

    判斷對象是不是可迭代的

>>> astr = "python"
>>> hasattr(astr,'__iter__')
True
>>> hasattr(3,'__iter__')
False

    5.1 append()和extend()區別

>>> lst = [1,2,3]
>>> lst.append(["tajzhang","blog"])
>>> lst
[1, 2, 3, ['tajzhang', 'blog']]
>>> len(lst)
4
>>> lst2 = [1,2,3]
>>> lst2.extend(["tajzhang","blog"])
>>> lst2
[1, 2, 3, 'tajzhang', 'blog']
>>> len(lst2)
5

    5.2 count 顯示列表中元素重複出現次數的方法

>>> la = [1,2,1,1,3]
>>> la.count(1)
3

    5.3 index 顯示元素索引位置,元素不存在就報錯

>>> la = [1,2,3,'a','b','c','tajzhang','python']
>>> la.index(3)
2

    5.4 inster 任意位置追加元素

>>> all_user = ['tajzhang','python','blog']
>>> all_user.insert(0,'github')
>>> all_user
>>> a = [1,2,3]
>>> a.insert(9,666)   #索引超過最大值則追加到最後
>>> a
[1, 2, 3, 666]

    5.5 remove和pop

       remove存在列表中即刪除,不存在列表中報錯,建議配合if判斷使用

>>> all_user
['github', 'tajzhang', 'python', 'blog']
>>> if "python" in all_user:
        all_users.remove("python")
        print(all_user)
    else:
       print("'python' is not in all_users")

    pop

>>> all_user
['github', 'tajzhang', 'python', 'blog']
>>> all_user.pop()
'blog'
>>> all_user
['github', 'tajzhang', 'python']
>>> all_user.pop(1)
'tajzhang'
>>> all_user
['github', 'python']
>>> all_user.pop(3)         #超出索引報錯
Traceback (most recent call last):
  File "<pyshell#117>", line 1, in <module>
    all_user.pop(3)
IndexError: pop index out of range

    5.6 reverse 倒序

>>> a = [3,5,1,6]
>>> a.reverse()
>>> a
[6, 1, 5, 3]
>>> a = [1,2,3,4,5]
>>> b = reversed(a)
>>> b
<list_reverseiterator object at 0x1023aee48>
>>> list(b)               #reverse不能實現反向迭代,可以使用reversed實現
[5, 4, 3, 2, 1]
>>> a
[1, 2, 3, 4, 5]
>>> a.reverse()

    5.7 sort  sorted()

>>> a
[1, 2, 3, 4, 5]
>>> a.reverse()
>>> a = [6,1,5,3]
>>> a.sort()
>>> a
[1, 3, 5, 6]
>>> a.sort(reverse=True)   #反向排序
>>> a
[6, 5, 3, 1]
>>> lst = ["python","java","c","pascal","basic"]
>>> lst.sort(key=len)            #根據key 排序相似excel
>>> lst
['c', 'java', 'basic', 'python', 'pascal']

 

 

六、比較字符串和列表

    6.1相同點

        二者都屬於序列類型,無論是組成列表的元素,仍是組成字符串的字符,均可以從左向右,依次用0,1,2...(-1,-2,3...)這樣的方式創建索引,均可以使用切片

    6.2區別

        最大區別,列表是能夠隨意修改的,字符串要從新賦值才能夠

    6.3多維列表

        字符串中每一個元祖只能是字符類型,列表中能夠是任何類型的數據

七、列表和字符串轉化

    7.1 str.split()

    7.2 "[sep]".join(list)

 

八、更pythonic的多值替換方法

lst2 = ["python",22,22,"python","linux","python","ubuntu"]
lst4 = ['python2' if x == 'pyhton' else x for x in lst2]  #多值替換
print(lst4)

lst3 = list(set(lst2))
print(lst3)

lstcache1 = [22,'linux']
lst5 = ['c++' if x in lstcache1 else x for x in lst3]  #去除相同元素,多元素替換同一個元素
print(lst5)


lstcache2 = {'python':'pythonIC','c++':'c#'}
lst6 = [lstcache2[x] if x in lstcache2 else x for x in lst5]  #根據字典映射關係替換
print(lst6)
相關文章
相關標籤/搜索