标签:
列表用于组织其它数值,即写在方括号之间、用逗号分隔开的数值列表。列表内的项目不必全是相同的类型。
列表的定义
1 student = [‘Tom‘, ‘Jack‘, ‘Avril‘]
添加元素
1 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 2 student *= 3 3 print(student) 4 5 6 # student中变量为name值的复制 7 name = [‘Jerry‘, ‘Lucy‘] 8 student = name[:] 9 print(student) 10 name.clear() 11 print(student) 12 13 14 # *得到的每一相同项指向同一内存地址 15 name = [‘Jerry‘]*3 16 print(name) 17 name.clear() 18 print(name) 19 20 # name2与name1指向同一内存地址 21 name1 = [‘Jerry‘] 22 name2 = name1 23 print(name2) 24 name1.clear() 25 print(name2) 26 27 # student中变量为name值的复制,与name不指向同一内存地址 28 name = [‘Jerry‘] 29 student = name*3 30 print(student) 31 name.clear() 32 print(student) 33 34 # append添加后,student中的[‘Jerry‘]与name变量指向同一内存地址 35 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 36 name = [‘Jerry‘] 37 student.extend(name) 38 print(student) 39 name.clear() 40 print(student) 41 42 # 同上,insert插入后,student中的[‘Jerry‘]与name变量指向同一内存地址 43 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 44 name = [‘Jerry‘] 45 student.insert(1, name) 46 print(student) 47 name.clear() 48 print(student) 49 50 # extend添加后,student中的[‘Jerry‘]为name值的复制 51 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 52 name = [‘Jerry‘] 53 student.extend(name) 54 print(student) 55 name.clear() 56 print(student)
删除元素
1 # 删除指定值的元素 2 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 3 student.remove(‘Tom‘) 4 print(student) 5 6 # 弹出栈顶元素 7 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 8 s = student.pop() 9 print(s) 10 print(student) 11 12 # 删除指定位置元素 13 student = [‘Tom‘, ‘Jack‘, ‘Avril‘] 14 del student[1] 15 print(student)
列表推导式
列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。
每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。如果希望表达式推导出一个元组,就必须使用括号。
将列表中每个数值乘三,获得一个新的列表:
>>> num = [1, 2, 3] >>> [3*n for n in num] [3, 6, 9]
可以用 if 子句作为过滤器:
>>> num = [1, 2, 3] >>> [3*n for n in num if n > 2] [9] >>> [3*n for n in numif n < 3] [3,6]
其他用法:
>>> vec1 = [2, 4, 6] >>> vec2 = [4, 3, -9] >>> [x*y for x in vec1 for y in vec2] [8, 6, -18, 16, 12, -36, 24, 18, -54] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8, 12, -54]
用列表推导式实现矩阵转置:
1 # 矩阵转置 2 matrix = [ 3 [1, 2, 3], 4 [4, 5, 6], 5 [7, 8, 9], 6 [10, 11, 12] 7 ] 8 9 # 方法一 10 newMatrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))] 11 print(newMatrix) 12 13 # 方法二 14 newMatrix = [] 15 for i in range(len(matrix[0])): 16 newMatrix.append([row[i] for row in matrix]) 17 print(newMatrix) 18 19 # 方法三 20 newMatrix = [] 21 for i in range(len(matrix[0])): 22 newRow = [] 23 for oldRow in matrix: 24 newRow.append(oldRow[i]) 25 newMatrix.append(newRow) 26 print(newMatrix)
标签:
原文地址:http://www.cnblogs.com/z941030/p/4831978.html