zoukankan      html  css  js  c++  java
  • Python基础:list

    0x00 简介 

    Python的列表对象是该语言提供的最通用的序列。列表是一个任意类型的对象的位置相关的有序集合,它没有固定大小。

    列表的特点可以概括为四点:1、有序的集合;2、通过偏移来索引;3、支持嵌套;4、类型可变。

    0x01 基本操作

    >>> L = [123, 'Captain', 3.14] #A list of three diffirent-type objects
    >>> len(L) #Number of items in the list
    3

    我们能够对列表进行索引、切片等操作

    >>> L[0] #Indexing by position
    123
    
    >>> L[:-1] #Slicing a list returns a new list
    [123, 'Captain']
    
    >>> L + ['Heisenberg', 456, 'Linux'] #Concatention makes a new list too
    [123, 'Captain', 3.14, 'Heisenberg', 456, 'Linux']
    
    >>> L # We're not changing the original list
    [123, 'Captain', 3.14]
    
     

    0x03 添加操作

    生成一个新列表

    >>> a = [1, 2, 3]
    >>> b = [4, 5, 6]
    >>> a+b
    [1, 2, 3, 4, 5, 6]  #generate a new list

    Extend方法:接收参数并将该参数的每个元素都添加到原有的列表中

    >>> a = [1, 2, 3]
    >>> b = [4, 5, 6]
    >>> a.extend(b) >>> a >>> [1,2,3,4,5,6]

    Append方法:添加任意对象到列表末端

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

    Insert方法:插入任意对象到列表中,可以控制插入位置

    >>> a = [1, 2, 3]
    >>> a.insert(1, 'a')
    >>> a
    [1, 'a', 2, 3]

    0x04 修改与删除

    >>> a = [1, 2, 3]
    >>> a[1] = 'change'
    >>> a
    [1, 'change' ,3]

    Del:通过索引删除指定位置的元素

    Remove:溢出列表中指定值的第一个匹配值

    Pop:返回最后一个元素并从list中删除它

    >>> a = [1, 2, 3, 4, 5, 5]
    >>> del a[0]
    >>> a 
    [2, 3, 4, 5, 5]
    
    >>> a.remove(5)
    >>> a
    [2,3,4,5]  #remove the first matching item

    >>> a.pop()
    5
    >>> a
    [2,3,4]

    0x05 成员关系

    in,not in可以判断某元素是否在该列表内,返回布尔值

    >>> a = [1,2,3,4]
    >>> 2 in a
    True
    >>> 5 not in a
    True

    0x06 列表推倒式

    >>> [x for x in range(1,11)]
    [1,2,3,4,5,6,7,8,9,10]
    >>> range(1,11,2)
    [1,3,5,7,9]
    
    >>> [x for x in range(1,11) if x % 2 == 1]
    [1,3,5,7,9]

    0x07 排序翻转

    Sort:将列表从小到大排列

    Reverse:将列表从大到小排列

    两种方法都是直接修改原列表

    >>> a = [33,11,22,44]
    >>> b = a.sort()
    >>> a
    [11,22,33,44]
    
    >>> c = a.reverse()
    >>> a 
    [44,33,22,11]
  • 相关阅读:
    hdu1238 Substrings
    CCF试题:高速公路(Targin)
    hdu 1269 迷宫城堡(Targin算法)
    hdu 1253 胜利大逃亡
    NYOJ 55 懒省事的小明
    HDU 1024 Max Sum Plus Plus
    HDU 1087 Super Jumping! Jumping! Jumping!
    HDU 1257 最少拦截系统
    HDU 1069 Monkey and Banana
    HDU 1104 Remainder
  • 原文地址:https://www.cnblogs.com/tzuxung/p/5691328.html
Copyright © 2011-2022 走看看