1. 程式人生 > 其它 >python 將列表中所有資料取反_Python資料結構中的列表

python 將列表中所有資料取反_Python資料結構中的列表

技術標籤:python 將列表中所有資料取反

0059925233ac685bef2a2d89b0b2ce3d.png

@Author:Runsen

資料結構

python有三種內建的資料結構:列表、元組和字典。

我們先講下列表

(1) 列表    list是處理一組有序專案的資料結構,列表是可變的資料結構。列表的專案包含在方括號[]中,

eg: [1, 2, 3], 空列表[]。判斷列表中是否包含某項可以使用in,

比如 l = [1, 2, 3]; print 1 in l; #True;

支援索引和切片操作;索引時若超出範圍,則IndexError;

使用函式len()檢視長度;使用del可以刪除列表中的項,eg: del l[0] # 如果超出範圍,則IndexError      list函式如下:

append(value)  #向列表尾新增項valuel = [1, 2, 2]l.append(3) #[1, 2, 2, 3]count(value)  #返回列表中值為value的項的個數l = [1, 2, 2]print( l.count(2)) # 2extend(list2)  # 向列表尾新增列表list2l = [1, 2, 2]l1 = [10, 20]l.extend(l1)print (l )  #[1, 2, 2, 10, 20]index(value, [start, [stop]])  # 返回列表中第一個出現的值為value的索引,如果沒有,則異常 ValueError

l = [1, 2, 2]a = 4try:    print( l.index(a))except ValueError, ve:    print( "there is no %d in list" % a    insert(i, value))      #向列表i位置插入項vlaue,如果沒有i,則新增到列表尾部l = [1, 2, 2]l.insert(1, 100)print l #[1, 100, 2, 2]l.insert(100, 1000)print l #[1, 100, 2, 2, 1000]pop([i])  #返回i位置項,並從列表中刪除;如果不提供引數,則刪除最後一個項;# 如果提供,但是i超出索引範圍,則異常IndexErrorl = [0, 1, 2, 3, 4, 5]print( l.pop()) # 5print( l) #[0, 1, 2, 3, 4]print( l.pop(1)) #1print( l) #[0, 2, 3, 4]

try:    l.pop(100)except IndexError, ie:    print( "index out of range")remove(value)  ---刪除列表中第一次出現的value,如果列表中沒有vlaue,則異常ValueErrorl = [1, 2, 3, 1, 2, 3]l.remove(2)print (l )#[1, 3, 1, 2, 3]try:    l.remove(10)except ValueError, ve:    print ("there is no 10 in list")

reverse()  ---列表反轉l = [1, 2, 3]l.reverse()print (l) #[3, 2, 1]sort(cmp=None, key=None, reverse=False)  ---列表排序l5 = [10, 5, 20, 1, 30]l5.sort()print( l5) #[1, 5, 10, 20, 30]l6 = ["bcd", "abc", "cde", "bbb"]l6.sort(cmp = lambda s1, s2: cmp(s1[0],s2[1]))print( l6) #['abc', 'bbb', 'bcd', 'cde']l7 = ["bcd", "abc", "cde", "bbb", "faf"]l7.sort(key = lambda s: s[1])print (l7) #['faf', 'abc', 'bbb', 'bcd', 'cde']