Python没有数组的说法,只有强大的列表!
普通列表
>>> member = ["xiao", "jia", "yu"]
>>> member
['xiao', 'jia', 'yu']
混合型列表
>>> mix = [1, 'XJY', 3.14, [1, 2, 3]]
>>> mix
[1, 'XJY', 3.14, [1, 2, 3]]
空列表
>>> empty = []
>>> empty
[]
向已有列表中添加元素,使用append() 参数!!,不过append只能一次性添加一个参数
>>> member.append("haha ")
>>> member
['xiao', 'jia', 'yu', 'haha ']
>>> len(member)
4
extend()可以添加一个扩展列表,也就是说可以一次性添加几个参数哦!
>>> member.extend(["hehe", "heihei"])
>>> member
['xiao', 'jia', 'yu', 'haha ', 'hehe', 'heihei']
插入一个新的元素并排序,使用insert()
>>> member.insert(1, "milan")
>>> member
['xiao', 'milan', 'jia', 'yu', 'haha ', 'hehe', 'heihei']
>>> member.insert(0, "milan")
>>> member
['milan', 'xiao', 'milan', 'jia', 'yu', 'haha ', 'hehe', 'heihei']
删除列表元素方法:
>>> member = ["xiao", "jia", "yu", "mudan", "yijing"]
>>> member
['xiao', 'jia', 'yu', 'mudan', 'yijing']
>>> member[1]
'jia'
1、remove(),可以指定删除哪一个数据
>>> member.remove('xiao')
>>> member
['jia', 'yu', 'mudan', 'yijing']
2、del, 可以按照列表的索引来删除元素,同时也可以直接删除整个列表!!
>>> del member[1]
>>> member
['jia', 'mudan', 'yijing']
>>> del member
>>> member
Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
member
NameError: name 'member' is not defined
3、pop(),出栈,也就是说默认每次是删掉列表最后一个元素,当然,也可以在括号里用数字指定要删除的元素的索引位置!
>>> member = ["xiao", "jia", "yu", "mudan", "yijing"]
>>> member.pop()
'yijing'
>>> name = member.pop()
>>> member
['xiao', 'jia', 'yu']
>>> member.pop(1)
'jia'
>>> member
['xiao', 'yu']
>>>
列表分片,可以一次性从列表中获取多个元素,也就是得到一个原列表的分片
>>> member = ["xiao", "jia", "yu", "mudan", "yijing"]
>>> member
['xiao', 'jia', 'yu', 'mudan', 'yijing']
>>> member[1:3] //获取的是原列表的起始索引值为1,终止索引值为3,但不包含3的列表分片
['jia', 'yu']
>>> member[1:] //获取的是原列表的起始索引值为1,终止为最后的列表分片
['jia', 'yu', 'mudan', 'yijing']
>>> member[:3] //获取的是原列表的起始到终止为3,但不包含3的列表分片
['xiao', 'jia', 'yu']
>>> member[:] //获取的是原列表的完整拷贝!!
['xiao', 'jia', 'yu', 'mudan', 'yijing']
>>>
网友评论