列表:
L.append(x) # x追加到L尾部 L.count(x) # 返回x在L中出现的次数 L.extend(m) # Iterable m的项追加到L末尾 L += m # 功能同L.extend(m) L.index(x, start, end) # 返回x在列表L(或者L[start:end])最左边出现的索引位置,否则报异常 L.insert(i, x) # 将x插入索引为i处 L.pop() # 返回并移除L最右边的项 L.pop(i) # 返回并移除索引为i的项 L.remove(x) # 从L中移除最左边的项x,找不到就抛异常 L.reverse() # 反转列表 L.sort(...) # 列表排序,参数可选
元祖:
''' 元祖可以类比字符串 元祖tuple的初始化 ''' t1 = tuple() t2 = () t3 = "venus", -28, "green", 19.74 ''' 元祖方法 ''' c = t3.count("green") # 统计个数 i = t3.index(-28) # 查看下标 ''' 交换值 ''' a, b = 1, 2 # a=1, b=2 a, b = b, a # a=2, b=1
命名元祖
''' 命名的元祖:计算商品总价 ''' from collections import namedtuple Sale = namedtuple("Sale","productid customerid date quantity price") sales = [] sales.append(Sale(432,921,"2008-09-14",3,7.99)) sales.append(Sale(419,874,"2008-09-15",1,18.49)) if __name__ == '__main__': total = 0 for sale in sales: total += sale.quantity * sale.price print("Total ${0:.2f}".format(total))
''' namedtuple("Foo","x y")函数返回tuple的子类,类名为Foo,属性为x y ''' from collections import namedtuple Aircraft = namedtuple("Aircraft","manufacturer model seating") Seating = namedtuple("Seating","minimum maximum") aircraft = Aircraft("Airbus", "A320-200", Seating(100, 200)) print(aircraft.seating.maximum) # 200 print("{0} {1}".format(aircraft.manufacturer, aircraft.model)) # Airbus A320-200 print("{0.manufacturer} {0.model}".format(aircraft)) # Airbus A320-200