1,在列表末尾添加一个值
>>> l = [ 10, 20 ] >>> l [10, 20] >>> l.append( 'ghostwu' ) >>> l [10, 20, 'ghostwu'] >>>
2,在列表的某个值前面插入一项,在'ghostwu'前面插入一项值'wukong'
>>> l [10, 20, 'ghostwu'] >>> l.insert( 2, 'wukong' ) >>> l [10, 20, 'wukong', 'ghostwu'] >>>
3,修改列表的某项值
>>> l [10, 20, 'wukong', 'ghostwu'] >>> l[0] = 100 >>> l [100, 20, 'wukong', 'ghostwu'] >>>
4,删除列表中的某个值
>>> l [100, 20, 'wukong', 'ghostwu'] >>> l.pop( 0 ) 100 >>> l [20, 'wukong', 'ghostwu'] >>>
>>> l [20, 'wukong', 'ghostwu'] >>> del l[2] >>> l [20, 'wukong'] >>>
>>> l [20, 'wukong', 'ghostwu', 'ghostwu', 'ghostwu'] >>> l.remove( 'ghostwu' ) >>> l [20, 'wukong', 'ghostwu', 'ghostwu'] >>>
5,对一个列表进行排序
>>> l = [ 3, 2, -1, 0, 10, -8, 100 ] >>> l [3, 2, -1, 0, 10, -8, 100] >>> l.sort() >>> l [-8, -1, 0, 2, 3, 10, 100] >>>
6,从一个已知的列表,用两种方式生成一个新的列表
>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> a [1, 2, 3] >>> b [4, 5, 6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6] >>>
>>> a = [1,2,3] >>> b = [4,5,6] >>> c = [] >>> a.extend( b ) >>> a [1, 2, 3, 4, 5, 6] >>> c.extend( a ) >>> c [1, 2, 3, 4, 5, 6] >>>
7,从列表的后面取出元素,一种是切片操作,另一种是pop+append组合
>>> a = [1,2,3,4,5] >>> a[-1:-3:-1] [5, 4] >>>
>>> a [1, 2, 3, 4, 5] >>> l=[] >>> l.append( a.pop() ) >>> l.append( a.pop() ) >>> l [5, 4] >>>
8,判断一个数在不在列表中
>>> a [1, 2, 3] >>> 1 in a True >>> '1' in a False
9,用列表推倒表达式,取出列表中所有的奇数
>>> a = [10, 13, 21, 22, 50, 56, 32, 31, 19] >>> res = [b for b in a if b % 2 != 0 ] >>> res [13, 21, 31, 19] >>>
根据列表[ 10, 13, 21, 22, 50, 56 ]生成字符串[ 'ghostwu10', 'ghostwu13', 'ghostwu21' ]
>>> l = [ 10, 13, 21, 22, 50, 56 ] >>> s = ["ghostwu %s" % x for x in l[0:3] ] >>> s ['ghostwu 10', 'ghostwu 13', 'ghostwu 21'] >>>
对列表的每一项+2,生成新的列表
>>> l [10, 13, 21, 22, 50, 56] >>> n = [ x + 2 for x in l ] >>> n [12, 15, 23, 24, 52, 58] >>>
10,用range和推导式生成[11,22,33,44,55,66]这样的列表
>>> l = [] >>> l = range( 11, 67, 11 ) >>> l [11, 22, 33, 44, 55, 66] >>>
>>> l = [] >>> l = [ x * 11 for x in range( 1, 7 ) ] >>> l [11, 22, 33, 44, 55, 66] >>>