码迷,mamicode.com
首页 > 其他好文 > 详细

列表和元组的操作

时间:2018-03-11 14:28:56      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:div   clear   extend   tuple   sci   pop   end   sort   规则   

列表(list)

append 向列表末尾追加

>>> a = [1, 2, 3]
>>> a.append(1)
>>> a
[1, 2, 3, 1]

insert 插入到指定下标

>>> a = [1, 2, 3]
>>> a.insert(1, 1)
>>> a
[1, 1, 2, 3]

remove

>>> a = [s, h, e, e, p]
>>> a.remove(e)
>>> a
[s, h, e, p]

del

>>> a = [s, h, e, e, p]
>>> del a[1]
>>> a
[‘s‘, ‘e‘, ‘e‘, ‘p‘]

pop 如果不传索引,默认删除最后的索引

>>> a = [s, h, e, e, p]
>>> a.pop()
p
>>> a
[s, h, e, e]
>>> a.pop(0)
s
>>> a
[h, e, e]

切片  左边的索引:右边的索引(:步长)

>>> a = [s, h, e, e, p]
>>> a[:]
[s, h, e, e, p]
>>> a[-4:-1:2] [h, e]

index 查指定元素的索引

>>> a = [s, h, e, e, p]
>>> a.index(h)
1

count 查指定元素的个数

>>> a = [s, h, e, e, p]
>>> a.count(e)
2

 

其它操作

clear 清空列表(python3)

>>> a = [s, h, e, e, p]
>>> a.clear()
>>> a
[]

reverse 反转

>>> a = [s, h, e, e, p]
>>> a.reverse()
>>> a
[p, e, e, h, s]

sort 排序(按照ascii排序规则)

>>> a = [2s, 5h, ce, Be, *p]
>>> a.sort()
>>> a
[*p, 2s, 5h, Be, ce]

extend 扩展

>>> a = [s, h, e, e, p]
>>> b = [1, 2, 3, 4, 5]
>>> a.extend(b)
>>> a
[s, h, e, e, p, 1, 2, 3, 4, 5]
>>> b
[1, 2, 3, 4, 5]

copy (python3,浅copy,只copy一层)

>>> a = [s, h, e, e, p, [today, 3-11]]
>>> b = a.copy()
>>> b
[s, h, e, e, p, [today, 3-11]]
>>> b[4] = e
>>> b
[s, h, e, e, e, [today, 3-11]]
>>> a
[s, h, e, e, p, [today, 3-11]]
>>> b[5][0] = tomorrow
>>> b
[s, h, e, e, e, [tomorrow, 3-11]]
>>> a
[s, h, e, e, p, [tomorrow, 3-11]]

 

元组(tuple,只读列表)

只有两个方法:index()和count()

列表和元组的操作

标签:div   clear   extend   tuple   sci   pop   end   sort   规则   

原文地址:https://www.cnblogs.com/allenzhang-920/p/8543655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!