列表 1、索引:序列中的所有元素都是有编号的--从0开始递增 >>> List=['hello','Jeff'] >>> List[0] 'hello' >>> Test='Hello' >>> Test[0] 'H' 使用负数索引时,Python会从右边,也就是从最后1个元素开始计数。最后一个元素的位置编号是-1 >>> List=['hello','Jeff'] >>> List[-1] 'Jeff' 字符串字面值,能够直接使用索引,而不需要一个变量引用他们: >>> 'hell'[0] 'h' 如果一个函数调用返回一个序列,那么可以直接对返回结果进行索引操作: >>> Name=raw_input("name:")[3] name:Jeff >>> Name 'f' 2、分片: 分片管理通过冒号相隔的两个索引来实现:第1个索引的元素是包含在切片内,而第2个则不包含在内 优雅的捷径: >>> numbers = [1,2,3,4,5,6] >>> numbers[3:6] [4, 5, 6] 从列表的结尾开始计数: >>> numbers = [1,2,3,4,5,6] >>> numbers[-3:-1] [4, 5] >>> numbers[-3:] [4, 5, 6] >>> numbers[:3] [1, 2, 3] 序列相加: >>> [1,2,3,4]+[5,6,7,8] [1, 2, 3, 4, 5, 6, 7, 8] 序列相乘: >>> 'python' * 5 'pythonpythonpythonpythonpython' >>> [32] * 5 [32, 32, 32, 32, 32] 成员资格: >>> users = ['main', 'foo', 'bar'] >>> 'foo' in users True >>> 'fo' in users False 最大、最小、长度: >>> numbers = [100,34,678] >>> max(numbers) 678 >>> min(numbers) 34 >>> len(numbers) 3 list函数: >>> list('hello') ['h', 'e', 'l', 'l', 'o'] 元素赋值: >>> x = [1,1,1] >>> x[1] = 2 >>> x [1, 2, 1] 删除元素: >>> del x[2] >>> x [1, 2] 分片赋值: >>> name = list('Perl') >>> name ['P', 'e', 'r', 'l'] >>> name[2:]=list('ar') >>> name ['P', 'e', 'a', 'r'] 列表方法append: >>> lst = [1,2,3] >>> lst.append(4) >>> lst [1, 2, 3, 4] 列表方法count:统计元素在列表中出现的次数 >>> lst = [1,2,3,5,5] >>> lst.count(5) 2 列表方法extend:可以在列表的末尾追加另一个列表的一个或多个值 >>> lst = [1,2,3,5 ] >>> lst = [1,2,3,5] >>> ex = [7,8,9] >>> lst.extend(ex) >>> lst [1, 2, 3, 5, 7, 8, 9] 列表方法index:查看某个值的索引位置: >>> user = ['jeff','lily'] >>> user.index('jeff') 0 列表方法insert:将对象插入列表中 >>> user ['jeff', 'lily'] >>> user.insert(1,'mother') >>> user ['jeff', 'mother', 'lily'] 列表方法remove: >>> user ['jeff', 'mother', 'lily'] >>> user.remove('jeff') >>> user ['mother', 'lily'] 列表方法reverse: >>> x = [1,2,3,4,5] >>> x.reverse() >>> x [5, 4, 3, 2, 1] 列表方法sort: >>> x = [6,1,3,5,2,0] >>> x.sort() >>> x [0, 1, 2, 3, 5, 6] 列表高级排序cmp(),key,reverse: >>> cmp(32,23) 1 >>> cmp(2,3) -1 >>> cmp(10,10) 0 >>> x = [6,1,3,5,2,0] >>> x.sort(cmp) >>> x [0, 1, 2, 3, 5, 6] >>> x = ['afdfj','fjkdasfjdkas', 'add','adb','acm','djfakdf'] >>> x.sort(key=len) >>> x ['add', 'adb', 'acm', 'afdfj', 'djfakdf', 'fjkdasfjdkas']