Google Python Course --- Lists

Python List

  • 能夠使用len獲取列表的長度,使用[]訪問列表中的元素;列表的索引從0開始數組

colors = ['red', 'blue', 'green']
  print colors[0]    ## red
  print colors[2]    ## green
  print len(colors)  ## 3

clipboard.png

  • 當把列表賦值給變量時,並非生成一個列表的拷貝,而只是使被賦值變量指向了該列表。app

b = colors     ###Does not copy the list

clipboard.png

For and IN

  • For var in List 是訪問數組元素最簡單的方式(其餘集合同樣適用)。[在循環的過程當中,不要增長或者刪除列表中的元素]curl

    squares = [1, 4, 9, 16]
    sum = 0
    for num in squares:
    sum += num
    print sum  ## 30
  • "IN"語句能夠輕鬆的測試某元素是否存在於列表中。
    根據測試結果,返回True/False函數

    list = ['larry', 'curly', 'moe']
    if 'curly' in list:
    print 'yay'

range

  • range(n)函數能夠返回從0開始到n-1的數字。測試

## print the numbers from 0 through 99
    for i in range(100):
    print i

List Methods

經常使用的List方法url

  • list.append(elem) --- 在列表末尾增長一個元素spa

  • list.insert(index,elem) --- 在給定的索引位置新增一個元素code

  • list.extend(list2) --- 將list2中的元素,新增到list列表末尾排序

  • list.index(elem) --- 查找元素elem,並返回該元素的索引索引

  • list.remove(elem) --- 查找元素elem,並刪除

  • list.sort() --- 對list列表排序(改變列表list),且沒有返回值

  • list.reverse() --- 對list列表轉置(改變列表list),且沒有返回值

  • list.pop(index) --- 根據index索引,移除,而且返回對應的元素

list = ['larry', 'curly', 'moe']
  list.append('shemp')         ## append elem at end
  list.insert(0, 'xxx')        ## insert elem at index 0
  list.extend(['yyy', 'zzz'])  ## add list of elems at end
  print list  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
  print list.index('curly')    ## 2

  list.remove('curly')         ## search and remove that element
  list.pop(1)                  ## removes and returns 'larry'
  print list  ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

List Slices 列表切片

切片([] 和 [:])

clipboard.png

aString = 'abcd'
 final_index = len(aString) - 1

本例中的最後一個索引是final_index.咱們能夠使用[:]訪問任意的子串。
對任何範圍內的[start:end],都不包括end.假設索引值是X,那麼start <=x < end

  • 正向索引
    正向索引時,索引值開始於0,結束於總長度減1

    >>> aString[0]
    'a'
    >>> aString[1:3]
    'bc'
    >>> aString[2:4]
    'cd'
    >>> aString[4]
    Traceback (innermost
    IndexError: string index out of range
  • 反向索引
    在進行反向索引操做時,是從-1開始,向字符串的開始方向計數,到字符串長度的負數爲索引的結束

    final_index = -len(aString)
    = -4
    >>> aString[-1]
    'd'
    >>> aString[-3:-1]
    'bc'
    >>> aString[-4]
    'a'
  • 默認索引
    若是開始索引或者結束索引未指定,則分別以字符串的第一個和最後一個索引值爲索引

    >>> aString[2:]
    'cd'
     >>> aString[1:]
    'bcd'
     >>> aString[:-1]
     'abc'
     >>> aString[:]
     'abcd'
相關文章
相關標籤/搜索