首页 > 编程语言 > 详细

Python_列表方法

时间:2020-03-09 22:29:04      阅读:60      评论:0      收藏:0      [点我收藏+]

1. 方法

技术分享图片

2. 例子

 (1)增加

1 >>> L = list(‘abc‘)
2 >>> L
3 [‘a‘, ‘b‘, ‘c‘]
4 >>> s = ‘def‘
1 >>> L.append(s)
2 >>> L
3 [‘a‘, ‘b‘, ‘c‘, ‘def‘]
1 >>> L.extend(s)
2 >>> L
3 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]
1 >>> L.insert(1, s)
2 >>> L
3 [‘a‘, ‘def‘, ‘b‘, ‘c‘]

(2)删除

  • del,pop,remove
1 >>> L = [‘a‘, ‘b‘, ‘c‘]
1 >>> del L[1]
2 >>> L
3 [‘a‘, ‘c‘]
1 >>> print(L.pop(1))
2 b
3 >>> L
4 [‘a‘, ‘c‘]
1 >>> L.remove(‘b‘)
2 >>> L
3 [‘a‘, ‘c‘]
  • 三种清空方式的比较

  参考地址:https://www.cnblogs.com/BackingStar/p/10986775.html

1 >>> L = list(‘abc‘)
2 >>> first = []
3 >>> last = []
4 >>> for i in L:
5       first.append(i)
6       last.append(first)
7       first = []
8 >>> last
9 [[‘a‘], [‘b‘], [‘c‘]]
1 >>> L = list(‘abc‘)
2 >>> first = []
3 >>> last = []
4 >>> for i in L:
5       first.append(i)
6       last.append(first)
7       first.clear()
8 >>> last
9 [[], [], []]
1 >>> L = list(‘abc‘)
2 >>> first = []
3 >>> last = []
4 >>> for i in L:
5       first.append(i)
6       last.append(first)
7       first *= 0
8 >>> last
9 [[], [], []]

 (3)修改

1 >>> L= [‘a‘, ‘b‘, ‘c‘]
2 >>> L[1] = ‘z‘
3 >>> L
4 [‘a‘, ‘z‘, ‘c‘]

(4)查找

1 >>> L = list(‘abcb‘)
2 >>> ‘b‘ in L
3 True
4 >>> ‘z‘ not in L
5 True
6 >>> L.index(‘b‘)
7 1

(5)计数

1 >>> L = list(‘abcb‘)
2 >>> L.count(‘b‘)
3 2

(6)重排

1 >>> L = list(‘bfeacd‘)
2 >>> L
3 [‘b‘, ‘f‘, ‘e‘, ‘a‘, ‘c‘, ‘d‘]
1 >>> L.reverse()
2 >>> L
3 [‘d‘, ‘c‘, ‘a‘, ‘e‘, ‘f‘, ‘b‘]
1 >>> L.sort()
2 >>> L
3 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]
1 >>> print(sorted(L))
2 [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]
3 >>> L
4 [‘b‘, ‘f‘, ‘e‘, ‘a‘, ‘c‘, ‘d‘]

(7)浅拷贝

1 >>> l1 = list(‘abc‘)
2 >>> l2 = l1.copy()
3 >>> id(l1) == id(l2)
4 False
5 >>> id(l1[0]) == id(l2[0])
6 True

注:浅拷贝和深拷贝的区别,详情见https://www.cnblogs.com/shz-blog/p/12451730.html

Python_列表方法

原文:https://www.cnblogs.com/shz-blog/p/12438954.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!