Python的列表

来源:互联网 发布:微信恶搞好友软件 编辑:程序博客网 时间:2024/04/29 21:40
python中的列表类似于C语言的数组(列表就是打了激素的数组)
  1. >>> #创建列表,不需要声明类型(Python变量标识符没有类型)
  2. >>> information= ["student0", "student1", "student2"]
  3. >>> print(information)
  4. ['student0', 'student1', 'student2']
  5. >>> print(information[0])
  6. student0
  7. >>> print(information[1])
  8. student1
  9. >>> print(information[2])
  10. student2
注意:在python中双引号和单引号没有区别

列表操作
使用append()添加或pop()删除列表末尾数据选项
  1. >>> information.append("student3")
  2. >>> print(information)
  3. ['student0', 'student1', 'student2', 'student3']
  4. >>> information.pop()
  5. 'student3'
  6. >>> print(information)
  7. ['student0', 'student1', 'student2']
使用extend()在列表末尾增加一个数据集合
  1. >>> information.extend(["student3","student4"])
  2. >>> print(information)
  3. ['student0', 'student1', 'student2', 'student3', 'student4']
使用remove()删除或insert()增加列表一个特定位置的数据选项
  1. >>> information.remove("student2")
  2. >>> print(information)
  3. ['student0', 'student1', 'student3', 'student4']
  4. >>> information.insert(2,2222)
  5. >>> print(information)
  6. ['student0', 'student1', 2222, 'student3', 'student4']
注意:py列表可以包含混合数据

dir(list)可查看到列表的更多用法(此处暂不详述)
  1. >>> dir(list)
  2. ['__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']

列表迭代操作
for循环处理任意大小列表
格式:
for 目标标识符 in 列表
    列表处理代码
  1. >>> number=[0,1,2,3]
  2. >>> for i in number:
  3. print(i)
  4. 0
  5. 1
  6. 2
  7. 3
while循环处理任意大小列表
  1. >>> number=[0,1,2]
  2. >>> count = 0
  3. >>> while count < len(number):
  4. print(number[count])
  5. count = count+1
  6. 0
  7. 1
  8. 2
注意:相比与C原因用{}界定代码段,python用缩进符界定。
注意:迭代处理时,能用for就不要用while,避免出现"大小差1"错误

在列表中存储列表(列表嵌套)
  1. >>> information=['a',['b','c']]
  2. >>> for i in information:
  3. print(i)
  4. a
  5. ['b', 'c']
从列表中查找列表
    先之前先介绍BIF中的函数isintance(),检测某个特定标识符是否包含某个特定类型数据。(即检测列表本身识是不是列表)
  1. >>> name=['sudent']
  2. >>> isinstance(name,list)
  3. True
  4. >>> num_name=len(name)
  5. >>> isinstance(num_name,list)
  6. False
    通过下面程序实现把列表中所有内容显示
  1. >>> information=['a',['b','c']]
  2. >>> for i in information:
  3. if isinstance(i,list):
  4. for j in i:
  5. print(j)
  6. else:
  7. print(i)
  8. a
  9. b
  10. c
dir(__builtins__)查看内建函数BIF有哪些

多重嵌套函数处理(使用递归函数)
  1. >>> information=['a',['b',['c']]]
  2. >>> def print_lol(the_list):
  3. for i in the_list:
  4. if isinstance(i,list):
  5. print_lol(i)
  6. else:
  7. print(i)
  8. >>> print_lol(information)
  9. a
  10. b
  11. c
定义函数标准格式
def 函数名(参数):
    函数组代码
0 0