Python入门教程3. 列表基本操作【定义、运算、常用函数】

前面简单介绍了Python字符串基本操作,这里再来简单讲述一下Python列表相关操作

1. 基本定义与判断

>>> dir(list) #查看列表list相关的属性和方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> lst = [] #定义一个空列表
>>> type(lst) #判断列表类型
<class 'list'>
>>> bool(lst) #bool()函数可判断对象真假,这里判断空列表lst为假
False
>>> print(lst)
[]
>>> a = ['1','False','laike']
>>> type(a)
<class 'list'>
>>> bool(a)
True
>>> print(a)
['1', 'False', 'laike']
>>> 

2. 列表常用操作函数:

append() 在列表末尾追加元素
count() 统计元素出现次数
extend() 用一个列表追加扩充另一个列表
index() 检索元素在列表中第一次出现的位置
insert() 在指定位置追加元素
pop() 删除最后一个元素(也可指定删除的元素位置)
remove() 删除指定元素
reverse() 将列表元素顺序反转
sort() 对列表排序
len() 计算列表元素个数

>>> list1 = [1,2,3,4,5,6]
>>> list1.append(1)
>>> list1.count(1)
2
>>> list2 = ['Tom',7]
>>> list1.extend(list2) # 列表list1后追加列表list2
>>> list1
[1, 2, 3, 4, 5, 6, 1, 'Tom', 7]
>>> list1.extend(['haha',8]) # 可以直接在extend函数的参数中使用列表
>>> list1
[1, 2, 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]
>>> list1.insert(2,'huhu') # 使用insert函数在序号2处添加元素'huhu'
>>> list1
[1, 2, 'huhu', 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]
>>> list1.pop() # pop()方法取出栈尾元素
8
>>> tmp = list1.pop() #可以将栈尾元素赋值便于使用
>>> tmp
'haha'
>>> list1.remove('huhu') #使用remove()函数删除指定元素'huhu'
>>> list1
[1, 2, 3, 4, 5, 6, 1, 'Tom', 7]
>>> list1.reverse()
>>> list1
[7, 'Tom', 1, 6, 5, 4, 3, 2, 1]
>>> list1.sort() #这里使用sort()排序,但是包含字符串类型与整数类型,会报错!
Traceback (most recent call last):
 File "<pyshell#18>", line 1, in <module>
  list1.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> list1.remove('Tom')
>>> list1.sort()
>>> list1
[1, 1, 2, 3, 4, 5, 6, 7]
>>> list1 = list(set(list1)) # 列表list去重(先使用set转换为不重复集合,再使用list类型转换回列表)
>>> list1
[1, 2, 3, 4, 5, 6, 7]
>>> l = len(list1) #使用len()方法求列表长度
>>> l
7
>>> list1.index(5) # index()获取元素出现的位置
4

简单入门教程~

基本一看就懂~O(∩_∩)O~

未完待续~~欢迎讨论!!