1. 程式人生 > >python的list型別常用操作

python的list型別常用操作

序列是Python中最基本的資料結構。序列中的每個元素都有索引,第一個索引是0,第二個索引是1,依此類推。從後面數的話,倒數第一個元素索引是-1。


下面是list的一些基本功能:

增:

append()追加
num_list = [1, 2, 3, 4, 5, 6]  
num_list.append(7)  
print(num_list) # 輸出[1, 2, 3, 4, 5, 6, 7]


insert(索引, 內容) 插入元素:
num_list = [1, 3, 4, 5]  
num_list.insert(1, 2)  
print(num_list) # 輸出[1, 2, 3, 4, 5]


extend() 擴充套件:
num_list = [1, 2, 3, 4]  
num_list2 = [5, 6, 7]  
num_list.extend(num_list2)  
print(num_list) # 輸出[1, 2, 3, 4, 5, 6, 7]  


直接相加(將兩個list相加,會返回到一個新的list物件):
num_list = [1, 2, 3, 4]  
num_list2 = [5, 6, 7]  
num_list3 = num_list + num_list2  
print(num_list) # 輸出[1, 2, 3, 4]  
print(num_list2) # 輸出[5, 6, 7]  
print(num_list3) # 輸出[1, 2, 3, 4, 5, 6, 7]  



刪:

remove() 移除某個指定值的元素:
num_list = [1, 2, 3, 4]  
num_list.remove(3)  
print(num_list) # 輸出[1, 2, 4]  


pop(index)移除列表中的一個元素(預設最後一個元素),並且返回該元素的值:
num_list = [1, 2, 3, 4]  
return_num = num_list.pop()  
print(num_list) # 輸出[1, 2, 3]  
print(return_num) # 輸出4  
  
num_list2 = [1, 2, 3, 4]  
return_num2 = num_list2.pop(2)  
print(num_list2) # 輸出[1, 2, 4]  
print(return_num2) # 輸出3 


del() 刪除:
num_list = [1, 2, 3, 4]  
del(num_list[1])  
print(num_list) # 輸出[1, 3, 4]  


clear() 清空:
num_list = [1, 2, 3, 4]  
num_list.clear()  
print(num_list) # 輸出[]  


改:

通過索引修改值:
num_list = [1, 2, 3, 4]  
num_list[2] = 5  
print(num_list) # 輸出[1, 2, 5, 4]


通過切片修改值:
num_list = [1, 2, 3, 4]  
num_list[1:3] = [5, 6, 7]  
print(num_list) # 輸出 [1, 5, 6, 7, 4] 



查:

通過索引獲取值:
num_list = [1, 2, 3, 4]  
num = num_list[2]  
print(num) # 輸出3  


切片(切片的特點是顧頭不顧尾):
num_list = [1, 2, 3, 4, 5, 6]  
num = num_list[2:4]  
print(num) # 輸出[3, 4]


count() 統計元素出現的次數:
num_list = [1, 2, 3, 4, 3, 6]  
print(num_list.count(3)) # 輸出2  


index() 獲取元素的索引,可指定列表起始位置:
num_list = [1, 2, 3, 4, 3, 6]  
print(num_list.index(3)) # 輸出2  
print(num_list.index(3, 3, 5)) # 輸出4  


用 in 查詢list是否包含某元素
num_list = [1, 2, 3, 4]  
print(2 in num_list) # 輸出True  
print(5 in num_list) # 輸出False  



其他:

len() 獲取list的長度:
num_list = [1, 2, 3, 4, 5, 6]  
print(len(num_list)) # 輸出 6  


迴圈list:
num_list = [1, 2, 3, 4]  
for i in num_list:  
    print(i)  
'''
輸出: 
1 
2 
3 
4 
'''  


reverse()反轉list:
num_list = [1, 2, 3, 4]  
num_list.reverse()  
print(num_list) # 輸出 [4, 3, 2, 1]  


sort()排序:
num_list = [4, 5, 2, 1, 3, 6, 8, 7]  
num_list.sort() # 從小到大  
print(num_list) # 輸出[1, 2, 3, 4, 5, 6, 7, 8]  
  
num_list = [4, 5, 2, 1, 3, 6, 8, 7]  
num_list.sort(reverse=True) # 從大到小  
print(num_list) # 輸出[8, 7, 6, 5, 4, 3, 2, 1]  



下面是list的原始碼:

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) -> None -- append object to end """  
        pass  
  
    def clear(self): # real signature unknown; restored from __doc__  
        """ L.clear() -> None -- remove all items from L """  
        pass  
  
    def copy(self): # real signature unknown; restored from __doc__  
        """ L.copy() -> list -- a shallow copy of L """  
        return []  
  
    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) -> None -- 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) -> None -- 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, key=None, reverse=False): # real signature unknown; restored from __doc__  
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """  
        pass  
  
    def __add__(self, *args, **kwargs): # real signature unknown  
        """ Return self+value. """  
        pass  
  
    def __contains__(self, *args, **kwargs): # real signature unknown  
        """ Return key in self. """  
        pass  
  
    def __delitem__(self, *args, **kwargs): # real signature unknown  
        """ Delete self[key]. """  
        pass  
  
    def __eq__(self, *args, **kwargs): # real signature unknown  
        """ Return self==value. """  
        pass  
  
    def __getattribute__(self, *args, **kwargs): # real signature unknown  
        """ Return getattr(self, name). """  
        pass  
  
    def __getitem__(self, y): # real signature unknown; restored from __doc__  
        """ x.__getitem__(y) <==> x[y] """  
        pass  
  
    def __ge__(self, *args, **kwargs): # real signature unknown  
        """ Return self>=value. """  
        pass  
  
    def __gt__(self, *args, **kwargs): # real signature unknown  
        """ Return self>value. """  
        pass  
  
    def __iadd__(self, *args, **kwargs): # real signature unknown  
        """ Implement self+=value. """  
        pass  
  
    def __imul__(self, *args, **kwargs): # real signature unknown  
        """ 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): # real signature unknown  
        """ Implement iter(self). """  
        pass  
  
    def __len__(self, *args, **kwargs): # real signature unknown  
        """ Return len(self). """  
        pass  
  
    def __le__(self, *args, **kwargs): # real signature unknown  
        """ Return self<=value. """  
        pass  
  
    def __lt__(self, *args, **kwargs): # real signature unknown  
        """ Return self<value. """  
        pass  
  
    def __mul__(self, *args, **kwargs): # real signature unknown  
        """ Return self*value.n """  
        pass  
 
    @staticmethod # known case of __new__  
    def __new__(*args, **kwargs): # real signature unknown  
        """ Create and return a new object.  See help(type) for accurate signature. """  
        pass  
  
    def __ne__(self, *args, **kwargs): # real signature unknown  
        """ Return self!=value. """  
        pass  
  
    def __repr__(self, *args, **kwargs): # real signature unknown  
        """ Return repr(self). """  
        pass  
  
    def __reversed__(self): # real signature unknown; restored from __doc__  
        """ L.__reversed__() -- return a reverse iterator over the list """  
        pass  
  
    def __rmul__(self, *args, **kwargs): # real signature unknown  
        """ Return self*value. """  
        pass  
  
    def __setitem__(self, *args, **kwargs): # real signature unknown  
        """ Set self[key] to value. """  
        pass  
  
    def __sizeof__(self): # real signature unknown; restored from __doc__  
        """ L.__sizeof__() -- size of L in memory, in bytes """  
        pass  
  
    __hash__ = None  




相關推薦

python的list型別常用操作

序列是Python中最基本的資料結構。序列中的每個元素都有索引,第一個索引是0,第二個索引是1,依此類推。從後面數的話,倒數第一個元素索引是-1。下面是list的一些基本功能:增:append()追加num_list = [1, 2, 3, 4, 5, 6] num_l

String型別常用操作

增(cteate): 1;*.string(); 把其他型別轉換成string型別;獲得新的string 建議寫法為 "*"; 2;str = str1.concat(str2); 把兩個字串型別拼接

二:Redis入門步驟(五大資料型別常用操作

1. 開啟一個 cmd 視窗 使用cd命令切換目錄到 C:\redis 執行 redis-server.exe redis.windows.conf 2.啟動: $ redis-server 3.檢視是否啟動: $ redis-cli 4.測試速度 redis-b

Redis 常用的五種資料型別操作

第一部分:五種型別的基礎操作 (文章分為兩部分,基礎操作和詳細操作)   一、Redis 字串(String) Redis 字串資料型別的相關命令用於管理 redis 字串值,基本語法如下: 語法 redis 127.0.0.1:6379> COMMAND K

21.13-21.17 redis常用操作,資料型別,操作鍵值,安全設定

21.13/21.14/21.15 redis常用操作  Redis常用操作 (string, list)  set key1 aminglinux  get key1  set key1 aming//第二次賦值會覆蓋  setnx

Redis的資料型別常用操作

五大資料型別 字串:String String是Redis最基本的型別,一個Key對應一個Value String型別是二進位制安全的,意思是Redis的String可以包含任何資料,例如一張jpg格式的圖片或者一個序列化的物件 一個Redis的字串型別Value

Python語法day2-常用資料型別操作

Python語法day2-常用資料型別及操作 數值 a,整型(int):2進位制(0b + 二進位制串),8進位制(0/0o + 八進位制串),10進位制,16進位制(0x + 16進位制串); b,浮點型(float):小數,也可以用科學計數法表示; c,複數(complex

Redis資料型別常用操作詳解

一、redis 簡介 redis適合放一些頻繁使用,比較熱的資料,因為是放在記憶體中,讀寫速度都非常快,一般會應用在下面一些場景,排行榜、計數器、訊息佇列推送、好友關注、粉絲。 首先要知道mysql儲存在磁盤裡,redis儲存在記憶體裡,redis既可以用來做持久儲存,也可以做快取,而目前大多數公司的儲存

python之路day03--資料型別分析,轉換,索引切片,str常用操作方法

資料型別整體分析 int :用於計算bool:True False 使用者判斷str:少量資料的儲存list:列表 儲存大量資料 上億資料[1,2,3,'zzy',[aa]]元組:只讀列表(1,23,'asdadas')dist:字典 鍵值對的形式儲存,關係型{'name':'小王八','age':16}

Python資料型別之str相關常用操作

name = "my \tname is alex" print(name.capitalize())  #首字母大寫 print(name.count("a"))    #統計字母的重複數量 print(name.center(50,"-"))

Python資料型別之dict相關常用操作

info = {     'stu1101': "TengLan Wu",     'stu1102': "LongZe Luola",     'stu1103': "XiaoZe Maliya"

Python資料型別之set相關常用操作

#set:集合去重(無序的) list_1 = set([1,4,5,7,3,6,7,9])   #結果{1, 3, 4, 5, 6, 7, 9} list_2 = set([2,6,0,66,22,8,4])  #結果{0, 2, 66, 4, 6, 8, 2

Python資料型別之list相關常用操作

列表:在其他程式語言中稱為“陣列”,是一種基本的資料結構型別。 關於列表的問題: 列表中元素使如何儲存的? 元素其實是記憶體地址,指向真正的元素,因為元素重複的時候,可以重複指向(省記憶體) 列表提供了哪些基本的操作? 列表操作包含以下函式: 1、cmp(list1, list2

Redis 資料型別常用操作指令

Redis 資料型別 redis支援五種資料型別:string(字串),hash(雜湊),list(列表),set(集合)及zset(sorted set:有序集合) **************************************************************

Redis 常用操作命令 之 string型別

string型別字串型別是 Redis 中最為基礎的資料儲存型別,它在 Redis 中是二進位制安全的,這便意味著該型別可以接受任何格式的資料,如JPEG影象資料或Json物件描述資訊等。在Redis中字串型別的Value最多可以容納的資料長度是512M。儲存如果設定的鍵不存

Redis入門之五大資料型別常用操作

注:本片博文基本都是從redis官網摘抄整理,感興趣的可以直接去官網檢視 另外,該網站也有比較全的redis命令參考http://redisdoc.com/ 一、String(字串) string是redis最基本的型別,你可以理解成與Memcached

byte 常用 操作

exceptio cat 移動 ror 位置 all const 長度 ear /** * 低位在前,高位在後 * * @param data * @return */ private byte[] intToBytes(int value) {

Rancher常用操作及名詞概念解析

開發 隔離 用戶登錄 項目組 做什麽 前言: 關於Rancher安裝請參考Rancher-Server部署,此文操作過程是基於以上部署環境進行演示。關於Rancher是做什麽,能完成哪些功能,有哪些優據點請自行了解。 本文主要介紹以下幾點什麽是環境如何添加環境什麽是應用棧如何添

Rancher常用操作及名詞解析

用戶登錄 項目組 做什麽 開發 隔離 前言: 關於Rancher安裝請參考Rancher-Server部署,此文操作過程是基於以上部署環境進行演示。關於Rancher是做什麽,能完成哪些功能,有哪些優據點請自行了解。 本文主要介紹以下幾點什麽是環境如何添加環境什麽是應用棧如何添