python入門到放棄(五)-基本數據類型之list列表

1.概述

列表是python的基本數據類型之一,是一個可變的數據類型,用[]方括號表示,每一項元素使用逗號隔開,能夠裝大量的數據

 

 #先來看看list列表的源碼寫了什麼,方法:按ctrl+鼠標左鍵點listpython

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -- append object to end """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y
                   
                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

list
View Code

 

2.列表的索引和切片

#列表和字符串同樣擁有索引和切片api

#索引:下標從0開始app

lst = ["趙四","劉能","謝大腳","謝騰飛","小蒙"]
print(lst[0]) #獲取第一個元素
#趙四
print(lst[1])
#劉能
print(lst[2])
#謝大腳

print(lst[3][2])   #
#索引下標從0開始,3就是謝騰飛,2就是在謝騰飛中切012,就是飛

print(lst[-2]) #負就是從後面切,從-1開始,-2就是謝騰飛

#切片ide

lst = ["趙四","劉能","謝大腳","謝騰飛","小蒙"]
print(lst[1:4]) #['劉能','謝大腳','謝騰飛']
#列表和字符串同樣,顧頭不顧尾,不能切到4print(lst[-3:-1]) #['謝大腳', '謝騰飛'],顧頭不顧尾因此不能切到小蒙print(lst[1::2])  #['劉能', '謝騰飛']
#從1開始到結束,每隔2個輸出一個print(lst[-1:-5:-2]) #['小蒙', '謝大腳']
#-1到-5,可是顧頭不顧尾就不能切到-5,-2就是從右往前切,每隔2個輸出一個

 

3.列表的增刪改查

#注意點:列表和str是不同的,list能夠發生改變,因此直接就在原來的對象上進行了操做
#例如:
lst = ["蔣小魚","張衝","魯炎","展大鵬"]
lst.append("阿甘")
print(lst) #['蔣小魚', '張衝', '魯炎', '展大鵬', '阿甘']

#3.1增長spa

#關鍵字
#append() 在後面追加
#insert() 指定位置添加
#extend() 迭代添加,也就是一個一個添加

#例子:3d

lst = ["蔣小魚","張衝","魯炎","展大鵬"]
lst.append("阿甘")
print(lst) #['蔣小魚', '張衝', '魯炎', '展大鵬', '阿甘']

lst.insert(2,"項羽")  #在魯炎的位置插入項羽,以前的元素相應的日後移
print(lst) #['蔣小魚', '張衝', '項羽', '魯炎', '展大鵬', '阿甘']

#若是使用字符串添加的話那麼就是迭代一個一個添加
lst.extend("巴朗")  #['蔣小魚', '張衝', '魯炎', '展大鵬', '巴', '朗']

#若是使用列表方式添加,那麼就是一個元素
lst.extend(["巴朗"]) #['蔣小魚', '張衝', '魯炎', '展大鵬', '巴朗']
print(lst)

#應用:交互輸入員工信息,而後按Q退出,再打印輸入的信息出來
# lst=[]
# while 1:
#     content = input("請輸入員工的信息,輸入Q退出:")
#     if content.upper() == 'Q':
#         break
#     lst.append(content)
# print(lst)
View Code

 

#3.2.刪除rest

#pop()  #指定位置刪除
#remove() #刪除元素
#clear()  #清空列表
#del()  #切片刪除

#例子:code

lst = ["蔣小魚","張衝","魯炎","展大鵬"]
lst.pop()   #不指定位置,默認刪除最後一個
print(lst) #['蔣小魚', '張衝', '魯炎']

el = lst.pop(2)  #刪除2號元素
print(el)  #能夠查看有沒有刪除
#魯炎
print(lst) #再返回列表查看有沒有刪了
# ['蔣小魚', '張衝', '展大鵬']

lst.remove("張衝") #指定刪除的元素
print(lst) #['蔣小魚', '魯炎', '展大鵬']

lst.remove("張三") #若是刪除不存在的元素就會報錯
print(lst) #報錯

lst.clear()  #清空
print(lst)

del lst[1:3] #切片刪除,由於顧頭不顧尾因此刪除1和2
print(lst) #['蔣小魚', '展大鵬']
View Code

 

#3.3.修改對象

# 一、索引修改
# 二、切片修改

#例子:blog

lst = ["蔣小魚","張衝","魯炎","展大鵬","黑臉"]
lst[1] = "烏雲"  #將1號元素修改爲烏雲,也就是張衝改爲烏雲
print(lst) #['蔣小魚', '烏雲', '魯炎', '展大鵬']

#切片:要注意後面的步長和元素的個數若是不對應的話就會報錯
lst[1:4:3] = ["龍大隊"] 
print(lst) #['蔣小魚', '龍大隊', '魯炎', '展大鵬', '黑臉']

# lst[1:4:3] = ["龍大隊","張三"]
#這樣就會報錯,由於步長是3,上面只能切到一個,可是修改了兩個,不對應,因此就會報錯
# print(lst)

lst[1:4] = ["大佬"] #將下標1-3替換成大佬
#若是切片沒有步長或者步長是1,則不用關心個數
print(lst)  #['蔣小魚', '大佬', '黑臉']
View Code

 

#3.4.查詢

#列表是一個可迭代對象,因此能夠進行for循環
 lst = ["張三","李四","王五","李六"]
 for el in lst:
     print(el)

 

4.列表的嵌套

#嵌套就是一層套着一層,列表套着列表
#
採用降維操做,一層一層的看, #就像洋蔥同樣,一層一層的撥開你的心

#例子:

lst = [1,"張三","蔣小魚",["魯炎","張衝",3,["黑臉","龍大隊","xiaotian",4],],"烏雲"]

#找到張衝
print(lst[3][1]) #張衝
#是按照從下標0開始找,3首先是找到第二個列表,而後再在第二個列表裏面找到1張衝

#找到黑臉和龍大隊
print(lst[3][3][0:2]) #['黑臉', '龍大隊']
#也是按照一層一層的找,記住是顧頭不顧尾的

#將xiaotian拿到,而後首字母大寫,再扔回去
s = lst[3][3][2]
s = s.capitalize()
lst[3][3][2] = s
print(lst) #[1, '張三', '蔣小魚', ['魯炎', '張衝', 3, ['黑臉', '龍大隊', 'Xiaotian', 4]], '烏雲']

#簡寫
# lst[3][3][2] = lst[3][3][2].capitalize()
# print(lst)

#將蔣小魚替換成參謀長
s = lst[2]
s = s.replace("蔣小魚","參謀長")
lst[2] = s
print(lst) #[1, '張三', '參謀長', ['魯炎', '張衝', 3, ['黑臉', '龍大隊', 'Xiaotian', 4]], '烏雲']

#簡寫
# lst[2] = lst[2].replace("蔣小魚","參謀長")
# print(lst)
View Code

 

5.列表的相關操做

#count() #查詢出現的次數
#sort()  #排序,默認升序
#len()   #列表的長度

#例子:

lst = ["蔣小魚","張衝","魯炎","展大鵬","黑臉","蔣小魚"]
c = lst.count("蔣小魚")  #查詢蔣小魚出現的次數
print(c) #2

lst.reverse()  #反向打印
print(lst) #['蔣小魚', '黑臉', '展大鵬', '魯炎', '張衝', '蔣小魚']

l = len(lst)  #計算列表的長度
print(l) #6

#排序,默認升序
lst = [1,2,3,44,11]  
lst.sort()
print(lst) #[1, 2, 3, 11, 44]

#降序
lst = [1,2,3,44,11] 
lst.sort(reverse=True) 
print(lst) #[44, 11, 3, 2, 1]
View Code

 

#循環刪除的坑點

######循環刪除列表中的每個元素(有坑)####
#方法:1.可使用clear()清空,
#       2.使用另一種方法,循環刪

#首先來個坑,刪不掉的
lst = [11,22,33,44,55]
for e in lst:
    lst.remove(e)
print(lst) #[22, 44]
#直接使用remove是刪除不了的,由於刪除的時候內部的索引在改變
# 當index=0的時候刪除0的字符,當index=1的時候就向下移動了一位,可是列表裏面的元素已經往前移填充了
#  因此當刪除11,22就變成了第0個索引,當下次刪除的時候就是刪除第一個索引33,而後就漏掉了22,後面一樣


#方法
#1.首先須要記錄刪除的東西
#2.而後循環要刪除的列表,刪除真正的列表

#例子:刪除性張的
lst = ["張衝","張國榮","張曼玉","蔣小魚"]
zhangs = [] #首先記錄性張
for el in lst:
    zhangs.append(el) #將以前的列表追加到zhangs裏面
for e in zhangs:
    lst.remove(e) #再刪除原列表
print(lst)  #[]
print(zhangs) #['張衝', '張國榮', '張曼玉', '蔣小魚']
View Code
相關文章
相關標籤/搜索