《Python 第二章》列表和元组

Python
最基本的数据结构 : 序列 『6种内建序列 - *元组和列表*』 元组vs列表 元组不能更改!
  元组 做 字典的key,不能用列表!
>>> edward = ['Uncle wang', 42]
>>> john = ['John Smith', 50]
>>> database = [edward, john]
>>> database
[['Uncle wang', 42], ['John Smith', 50]]
通用序列操作 : 索引,分片,加,乘,计算序列长度,找出最大元素,找出最小元素。
>>> greeting = 'Hello'
>>> greeting[-2]
'l'
>>> four = raw_input('Year : ')[3]
Year : 200569
>>> four
'5'
>>> tag='hello jim world wow hehe'
>>> tag[3:-2]
'lo jim world wow he'
>>> tag[3:]
'lo jim world wow hehe'
>>> tag[:3]
'hel'
>>> tag[:]
'hello jim world wow hehe'
>>> num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> num[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> num[0:10:2]
[1, 3, 5, 7, 9]
>>> num[0:10:-2]
[]
>>> num[10:0:-2]
[10, 8, 6, 4, 2]
* 两个同类型的序列可以相加 *
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'python'*5
'pythonpythonpythonpythonpython'
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

* 成员资格 *

>>> name = 'roobby_Chan'
>>> 'oob' in name
True
>>> 'oobc' in name
False
* 长度,最大值,最小值 *
>>> nums = [100, 34, 678]
>>> len(nums)
3
>>> max(nums)
678
>>> min(nums)
34
* 列表 :Python 的 “苦力” *
 列表不同与 元组 和 字符串的地方 : 列表是可变的
* list函数 *
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
* 基本的列表操作 *
>>> x = [1, 1, 1]
>>> x[1] = 2      # 赋值操作
>>> x
[1, 2, 1]
>>> names = ['Alice', 'Beth', 'Ceil', 'Dee']
>>> del names[2]  # 删除操作
>>> names
['Alice', 'Beth', 'Dee']
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar')  # 分片
>>> name
['P', 'e', 'a', 'r']
>>> nums = [1,5]           
>>> nums[1:1]=[2,3,4]     # 分片
>>> nums
[1, 2, 3, 4, 5]
* 列表方法 *
>>> lst = [1, 2, 3]
>>> lst.append(4)   #append()
>>> lst
[1, 2, 3, 4]
>>> lst.count(2)   # count
1
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)   # extend() 效率比较高
>>> a
[1, 2, 3, 4, 5, 6]
>>> a+b
[1, 2, 3, 4, 5, 6, 4, 5, 6]
>>> a[len(a):] = b
>>> a
[1, 2, 3, 4, 5, 6, 4, 5, 6]
>>> a.index(4)   # index()
3
>>> a.insert(3, 'four')
>>> a
[1, 2, 3, 'four', 4, 5, 6, 4, 5, 6]
>>> a.pop()      # pop()
6
>>> a
[1, 2, 3, 'four', 5, 6, 4, 5]
>>> a.pop(1)
2
>>> a
[1, 3, 'four', 5, 6, 4, 5]
>>> a.remove(5)   # remove()
>>> a
[1, 3, 'four', 6, 4, 5]
>>> a.reverse()   # reverse()
>>> a
[5, 4, 6, 'four', 3, 1]
>>> a.sort()      # sort()
>>> a
[1, 3, 4, 5, 6, 'four']
>>> b = a[:]      # 副本赋值给 b
>>> b.sort()
>>> b
[1, 3, 4, 5, 6, 'four']
>>> y = sorted(b) # 获取已排序列表副本
>>> y
[1, 3, 4, 5, 6, 'four']
>>> a.sort(reverse=True) # a.sort(reverse=True) 
>>> a
['four', 6, 5, 4, 3, 1]
* 元组  不可变序列 *
>>> 1, 2, 3
(1, 2, 3)
>>> 3*(40+2)
126
>>> 3*(40+2,)
(42, 42, 42)
* tuple 函数 * 功能是 :序列转化为元组
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> x = 1, 2, 3  基本元组操作
>>> x[1]
2
* 小结 *
 *1 序列
 *2 成员资格
 *3 方法
 本章的新函数
 cmp(x, y)
 len(seq)
 list(seq)
 max(args) 返回序列或者参数集合中的最大值
 min(args) 
 reversed(seq) 对序列进行反向迭代
 sorted(seq)  返回已排序的包含seq所有元组的列表
 tuple(seq)   把序列转化为元组
下一章 : 字符串








原文地址:https://www.cnblogs.com/robbychan/p/3787218.html