Python基本資料型別之list

morra發表於2016-10-13

一、建立列表:


li = []
li = list()
name_list = ['alex', 'seven', 'eric']

name_list = list(['alex', 'seven', 'eric'])

二、基本操作:

索引

name_list = ["eirc","morra","tommy"]
print(name_list[0])    #eirc
print (name_list[2])     #'tommy'
print (name_list[-1])    #'tommy'
print (name_list[-2])    #'morra'
print (name_list[1:])    #['morra', 'tommy']
print(name_list.index('eirc'))     #輸出eric的索引
print(type(li[2]))        #<class 'str'>索引取出來後是元素的型別

索引的特殊用法

>>> li=[1,2,3,4,5,6,7,8]
>>> li[::-1]        #倒敘
[8, 7, 6, 5, 4, 3, 2, 1]
>>> li[::-2]        #元素之間間隔2
[8, 6, 4, 2]
>>> li[::-3]
[8, 5, 2]

切片

name_list = ["eirc","morra","tommy"]
print(name_list[0:2])       #['eirc', 'morra']
print(name_list[2:len(name_list)])       #['tommy']
print(type(li[1:2]))        #<class 'list'>切片取出之後是列表型別

追加與擴充套件

追加:

name_list = ["eirc","morra","tommy"]
name_list.append('456')     #直接操作物件,無返回值
print(name_list)

OUTPUT:
['eirc', 'morra', 'tommy', '456']

擴充套件:

name_list = ["eirc","morra","tommy"]
name_list2 = ["bom"]
name_list.extend(name_list2)       #直接操作物件,無返回值
print(name_list)

OUTPUT:
['eirc', 'morra', 'tommy', 'bom']

插入

name_list = ["eirc","morra","tommy"]
name_list.insert(1,'hello')        #直接操作物件,無返回值
print(name_list)

OUTPUT:
['eirc', 'hello', 'morra', 'tommy']

刪除

pop():刪除尾部元素

name_list = ["eirc","morra","tommy"]
temp = name_list.pop()        #刪除尾部元素,並把所刪除的元素存到一個新值裡
print(name_list)
print(temp)

OUTPUT:
['eirc', 'morra']
tommy

remove():刪除指定元素,只能有一個引數(匹配從左到右的第一個),不能加index

name_list = ["eirc","morra","tommy"]
name_list.remove("morra")
print(name_list)

OUTPUT:
['eirc', 'tommy']

del:刪除指定元素,可以使用索引和切片

name_list = ["eirc","morra","tommy","bom"]
del name_list[0]
print(name_list)

del name_list[1:2]      
print(name_list)
OUTPUT:
['morra', 'tommy', 'bom']
['morra', 'bom']

列表指令碼操作符

列表對+和的操作符與字串相似。+號用於組合列表,號用於重複列表,例如:

print len([1, 2, 3]); #3
print [1, 2, 3] + [4, 5, 6]; #[1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4; #['Hi!', 'Hi!', 'Hi!', 'Hi!']
print 3 in [1, 2, 3] #True
for x in [1, 2, 3]: print x, #1 2 3

拷貝

list的拷貝有5種方式

#1
listb = lista[:]

#2
listb = list(lista)

#3
listb = [i for i in lista]

#4
import copy
listb = copy.copy(lista)               #淺拷貝

#5
import copy
 listb = copy.deepcopy(lista)      #深拷貝

補充

注意:在業務程式碼裡,一般會把列表寫成 a = [1,2,3,]的形式,在使用特定框架時會用到。

三、可迭代性

一般來說只要可以用for迴圈,我們就認為它是可迭代的

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """

判斷一個資料型別是否可迭代:

from collections import Iterable    #使用collections模組的Iterable型別來判斷

li = [1,2,3,4]
ret = isinstance(li,Iterable)
print(ret)    #True

字串轉列表

s = "你好morra"
li = list(s)
print(li)

OUTPUT:
['你', '好', 'm', 'o', 'r', 'r', 'a']

元組轉列表

tu = ("你好","alex")
li = list(tu)
print(li)

OUTPUT:
['你好', 'alex']

字典轉列表

dic = {'k1':'hello','k2':'morra'}
l3 = list(dic)              #字典在迴圈的時候預設只迴圈key
print(l3)

l4 = list(dic.values())
print(l4)

l5 = list(dic.items())
print(l5)

OUTPUT:
['k2', 'k1']
['morra', 'hello']
[('k2', 'morra'), ('k1', 'hello')]

四、原始碼

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): 
        """追加,直接操作物件,無返回值"""
        """ L.append(object) -> None -- append object to end """
        pass

    def clear(self): 
        """ L.clear() -> None -- remove all items from L """
        pass

    def copy(self): 
        
        """ L.copy() -> list -- a shallow copy of L """
        return []

    def count(self, value): 
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): 
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): 
        """
        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): 
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): 
        """
        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): 
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): 
        """列表倒序"""
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, key=None, reverse=False): 
        """"快速排序,問:包含字母數字中文的列表該怎麼排序?"""
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

    def __add__(self, *args, **kwargs): 
        """ Return self+value. """
        pass

    def __contains__(self, *args, **kwargs): 
        """ Return key in self. """
        pass

    def __delitem__(self, *args, **kwargs): 
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): 
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): 
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y): 
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs): 
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): 
        """ Return self>value. """
        pass

    def __iadd__(self, *args, **kwargs): 
        """ Implement self+=value. """
        pass

    def __imul__(self, *args, **kwargs): 
        """ Implement self*=value. """
        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, *args, **kwargs): 
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): 
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): 
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): 
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs): 
        """ Return self*value.n """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): 
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): 
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs): 
        """ Return repr(self). """
        pass

    def __reversed__(self): 
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, *args, **kwargs): 
        """ Return self*value. """
        pass

    def __setitem__(self, *args, **kwargs): 
        """ Set self[key] to value. """
        pass

    def __sizeof__(self): 
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

相關文章