列表
列表是一组有序的数据集合,可以将各种各样的数据有序的存放在列表中,并且可以对其进行增删改查,以及遍历。
例子:
>>> shopping_list=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘] >>> shopping Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘shopping‘ is not defined >>> shopping_list [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘] ##切片 >>> len(shopping_list) #通过len()内置函数查找列表元素个数 6 >>> shopping_list[2] #第三个元素 ‘c‘ >>> shopping_list[0] #第一个元素 ‘a‘ >>> shopping_list[-1] #最后一个元素 ‘f‘ >>> shopping_list[-3] #倒数第三位元素 ‘d‘ >>> shopping_list[-4] #倒数第四个元素 ‘c‘ >>> shopping_list[8] #超出范围 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range >>> shopping_list[0:3] #取0到第三个元素,不包括第四个,0可以不写 [‘a‘, ‘b‘, ‘c‘] >>> shopping_list[:3] #同上 [‘a‘, ‘b‘, ‘c‘] >>> shopping_list[2:5] #取第3至第5个元素 [‘c‘, ‘d‘, ‘e‘] >>> shopping_list[:-3] #取从0至倒数第3个元素 [‘a‘, ‘b‘, ‘c‘] >>> shopping_list[-3:] #取最后3个元素 [‘d‘, ‘e‘, ‘f‘] >>> shopping_list[1:6:2] #1-6,每隔2个元素取1个 [‘b‘, ‘d‘, ‘f‘] >>> shopping_list[::2] #从头到尾每隔一个取一个 [‘a‘, ‘c‘, ‘e‘] ##增删改 >>> shopping_list.append(‘g‘) #向列表后面追加一个元素 >>> shopping_list [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] >>> shopping_list.pop() #删除最后一个元素 ‘g‘ >>> shopping_list.remove(‘f‘) #删除叫”f“的元素,如果有多个f,那会从左边数找到的第一个 >>> shopping_list[2] ‘c‘ >>> shopping_list[2]=‘C‘ #将索引为2的元素改成”C“,原来是小写的! >>> shopping_list [‘a‘, ‘b‘, ‘C‘, ‘d‘, ‘e‘] >>> shopping_list.insert(3,"haha") #插入一个新元素,索引为3 >>> shopping_list [‘a‘, ‘b‘, ‘C‘, ‘haha‘, ‘d‘, ‘e‘] >>> shopping_list.index(‘haha‘) #返回‘haha’的索引值,如果有多个相同元素,则返回匹配的第一个 3 >>> shopping_list.append(‘haha‘) #再插多个进去 >>> shopping_list [‘a‘, ‘b‘, ‘C‘, ‘haha‘, ‘d‘, ‘e‘, ‘haha‘] >>> shopping_list.count(‘haha‘) #统计‘haha’的元素个数 2 >>> list2=[‘h‘,‘i‘,‘j‘] #创建一个新列表 >>> shopping_list.extend(list2) #把上面的新列表合并到shopping_list >>> shopping_list [‘a‘, ‘b‘, ‘C‘, ‘haha‘, ‘d‘, ‘e‘, ‘haha‘, ‘h‘, ‘i‘, ‘j‘] >>> shopping_list.sort() #将列表排序 >>> shopping_list [‘C‘, ‘a‘, ‘b‘, ‘d‘, ‘e‘, ‘h‘, ‘haha‘, ‘haha‘, ‘i‘, ‘j‘] >>> shopping_list.reverse() #将列表反转 >>> shopping_list [‘j‘, ‘i‘, ‘haha‘, ‘haha‘, ‘h‘, ‘e‘, ‘d‘, ‘b‘, ‘a‘, ‘C‘] >>> del shopping_list[3:8] #删除索引3至8的元素,不包括8 >>> shopping_list [‘j‘, ‘i‘, ‘haha‘, ‘a‘, ‘C‘] >>> for i in shopping_list: #遍历列表 ... print i ... j i haha a C
元组
另一种有序列表叫元组。tupel一旦初始化就不能修改。
元组没有append()、insert()这样的方法,其它获取元素的 方法和list是一样的。
不可变的元组,代码更安全
>>> student=(‘yaobin‘,‘hy‘,‘nimei‘) >>> student[0] ‘yaobin‘ >>> student[1] ‘hy‘ >>> student[1]=‘hyhy]‘ #不能修改 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ‘tuple‘ object does not support item assignment >>> t = (1,2) >>> t (1, 2) >>> t = () #空元组 >>> t () >>> t = (1) #定义的不是元组了,是1这个数 >>> t 1 >>> t = (1,) #防止歧义,要加, >>> t (1,) #这个才是元组
原文:http://www.cnblogs.com/binhy0428/p/5083314.html