首页 > 代码库 > Beginning Python From Novice to Professional (3) - 列表操作
Beginning Python From Novice to Professional (3) - 列表操作
列表操作
list函数:
>>> list('hello') ['h', 'e', 'l', 'l', 'o']改变列表:
>>> x=[1,1,1] >>> x[1]=2 >>> x [1, 2, 1]删除元素:
>>> names = ['wu','li','zhao','qian'] >>> del names[1] >>> names ['wu', 'zhao', 'qian']分片赋值:
>>> name = list('perl') >>> name ['p', 'e', 'r', 'l'] >>> name[2:] = list('ar') >>> name ['p', 'e', 'a', 'r']
>>> num = [1,2,3,4,5] >>> num[1:4]=[] #从1位开始但不包括4位 >>> num [1, 5]append 列表末尾添加新元素:
>>> lst = [1,2,3] >>> lst.append(4) >>> lst [1, 2, 3, 4]count 统计元素的个数:
>>> ['we','have','we','a','dog'].count('we') 2extend 扩展列表:
>>> a = [1,2,3] >>> b = [4,5,6] >>> a.extend(b) >>> a [1, 2, 3, 4, 5, 6]index 找出第一个匹配项的位置:
>>> sentence = ['I','have','a','little','dog'] >>> sentence.index('little') 3insert 将对象插入列表:
>>> num = [1,2,3,5,6,7] >>> num.insert(3,'four') >>> num [1, 2, 3, 'four', 5, 6, 7]pop 移除列表元素,默认最后一个:
>>> x = [1,2,3] >>> x.pop() 3 >>> x [1, 2] >>> x.pop(0) 1 >>> x [2]结合append:
>>> x = [1,2,3] >>> x.append(x.pop()) >>> x [1, 2, 3]remove 移除列表中的第一个匹配项:
>>> x = ['to','be','or','not','to','be'] >>> x.remove('be') >>> x ['to', 'or', 'not', 'to', 'be']reverse 反向存放元素:
>>> x = [1,2,3] >>> x.reverse() >>> x [3, 2, 1]sort 排序:
>>> x = [4,6,2,1,7,9] >>> x.sort() >>> x [1, 2, 4, 6, 7, 9]
>>> x.sort(reverse=True) >>> x [9, 7, 6, 4, 2, 1] >>> x.sort(reverse=False) >>> x [1, 2, 4, 6, 7, 9]
Beginning Python From Novice to Professional (3) - 列表操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。