列表 list
[a,b,c,d] 通过 list 类创建的对象, 中括号括起来, 中间以逗号分割每个元素
列表中的元素可以是: 数字, 字符串'', 嵌套列表, 布尔值.....all
可以被修改
- 选择
[][]连续查找
- test = ['a','ab','abc','abcd']
- l = test[0] # 返回结果 'a'
- li = test[1][1] # 返回结果 'b'
- 修改
- test = ['a','ab','abc','abcd']
- test[2] = 120
- print(test)
- # 返回结果 ['a', 'ab', 120, 'abcd']
- 删除 del
- test = ['a','ab','abc','abcd']
- del test[2]
- print(test)
- # 返回结果 ['a', 'ab', 'abcd']
- 转换
- 对于字符串转换列表, 直接 list(), 但数字不能直接转换
- test = 'abcd'
- new_test = list(test)
- print(new_test)
- # 返回结果 ['a', 'b', 'c', 'd']
- 把列表转换成字符串, for 循环一个一个处理, 既有数字又有字符串
- test = [1,2,'ab']
- s = ''
- for i in test:
- s = s + str(i)
- print(s)
- # 返回结果 12ab
- 如果列表中全是字符串没有数字
- test = ['12','ab']
- v = ''.join(test)
- print(v)
- # 返回结果 12ab
- - def append(self, object: _T)
在原列表内最后追加一个元素, 可以数字, 文字, 列表等
- test = ['12','ab']
- test.append('abc')
- print(test)
- # 返回结果 ['12', 'ab', 'abc']
- - def clear(self)
全部清空列表
- def copy(self)
浅拷贝
- test = ['12','ab']
- v = test.copy()
- print(v)
- # 返回结果 ['12','ab']
- - def count(self, object: _T)
计算列表中某元素出现的次数
- def extend(self, iterable: Iterable[_T])
在愿列表中最后追加 n 个元素, 内部循环, 多次追加, 可以数字, 文字, 列表等
参数可迭代对象
- test = ['12','ab']
- test.extend(['abd'])
- print(test)
- # 返回结果 ['12', 'ab', 'abd']
- test.extend('abc')
- print(test)
- # 返回结果 ['12', 'ab', 'abd', 'a', 'b', 'c']
@ 注意: extend([])当中的 [] 不要漏
- def index(self, object: _T, start: int = ..., stop: int = ...)
找某个值的索引位置
- test = ['12','ab']
- v = test.index('ab')
- print(v)
- # 返回结果 1
- - def insert(self, index: int, object: _T)
插入 int 是索引位置
- test = ['12','ab']
- test.insert(2,'abc')
- print(test)
- # 返回结果 ['12', 'ab', 'abc']
- - def pop(self, index: int = ...)
删除某个值, 并获取删除的值, 默认是最后一个
- test = ['12','ab']
- v = test.pop(1)
- print(test)
- print(v)
- # 返回结果
- # # ['12']
- # # ab
- - def remove(self, object: _T)
删除某个值, 如有重复, 默认删除左边第一个
- def reverse(self)
将列表中的序列顺序全部反转
- test = ['12','ab']
- test.reverse()
- print(test)
- # 返回结果 ['ab', '12']
- - def sort(self,key=none, reverse=false)
将序列中的数字按照大小进行排序
- test = [11,22,44,33,11]
- test.sort()
- print(test)
- # 返回结果 [11, 11, 22, 33, 44]
- test.sort(reverse=True)
@注意: reverse=True True 首字母必须是大写, python 固定格式
- print(test)
- # 返回结果 [44, 33, 22, 11, 11]
来源: http://www.bubuko.com/infodetail-3460072.html