Python中list列表的常见操作

乎语百科 303 0

Python的list是一个列表,用方括号包围,不同元素间用逗号分隔。

列表的数据项不需要具有相同的类型。(列表还可以嵌套,即列表中的列表)

每个元素都有一个索引(表示位置),从0开始;可以用索引-1表示最后一个元素,-2表示倒数第二个元素。

(1)获取列表长度,用len( ) 方法:

list1 = [ 1, 2 , 3, 4]
print( len(list1) );   #  4

(2)删除列表元素,用索引找列表元素:

list1 = [1,2,3,4,5,6,7,8,9,10]
del list1[2] # 或del list[2]
print(list1) # [1, 2, 4, 5, 6, 7, 8, 9, 10]
print(list1[1:-1]) # [2, 4, 5, 6, 7, 8, 9]

(3)迭代和遍历:

list1 = [ 1, 2 , 3, 4]
for x in list1:
    print(x)

遍历 [start,end),间隔为 span,当 span>0 时顺序遍历, 当 span<0 时,逆着遍历。 start 不输入则默认为 0,end 不输入默认为长度。

list = [i for i in range(0,15)]
print(list) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(list[::2]) #[0, 2, 4, 6, 8, 10, 12, 14]

(4)加号和乘号:+ 号用于组合列表,* 号用于重复列表。也支持+=或*=运算符

list1 = [ 1, 2, 3, 4]
list2 = [ 5, 6, 7, 8]
list = list1 + list2
print(list);  # [1,2,3,4,5,6,7,8]
print(list1*2); #[1,2,3,4,1,2,3,4]

(5)合并列表 (除了+外),还有append( )和extend( )方法, 注意区别,append( )是将列表整体作为一个元素加入,extend( )是把列表每个元素加入; 两者都会直接修改原列表list1数据

list1 = [ 1, 2, 3, 4]
list2 = [ 5, 6, 7, 8]
list1.append(list2)
print(list1) #[1, 2, 3, 4, [5, 6, 7, 8]]

list1 = [ 1, 2, 3, 4]
list2 = [ 5, 6, 7, 8]
list1.extend(list2)
print(list1) #[1, 2, 3, 4, 5, 6, 7, 8]

还有一种插入列表的方法,叫切片,可以指定插入位置:

aList = [1,2,3,4]
bList = ['www', 'pythontab.com']
aList[1:1] = bList
print(aList) #[1, 'www', 'pythontab.com', 2, 3, 4]

(6)Python的以下函数可用于列表:

min(list) 求最大值
max(list) 求最小值
list(seq) 将元组转换为列表

(7)list的其他方法:

list.count(obj) 统计某个元素在列表中出现的次数
list.reverse()  反向列表中元素
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj)  将对象按位置插入列表
list.pop([index=-1])  移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj)  移除列表中某个值的第一个匹配项,在原列表上删除。
list.sort(key=None, reverse=False) 对原列表进行排序
list.clear() 清空列表
list.copy()  复制列表

(8)创建二维列表 例如,3行5列的二维列表

list_2d = [[col for col in range(5)] for row in range(3)]
print(list_2d) #[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

(9)列表推导式: 例如: squares = [x**2 for x in range(10)] 会生成[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]的列表

(10) 列表的切片表示 形式是[ startIndex : endIndex : step ],索引为0或不写表示第一个元素,索引可以为-1表示最后一个元素,索引为end或不写表示最后一个元素加一,step为-1表示反向走。 结果中包含startIndex元素,不包含endIndex元素。

因此 list1[::-1]可以表示list1的反序。

特别的,list1[:]仍表示list1自己。

Python中的字符串也可以使用切片表示。

更详细的,可以参考Python官方文档 python.org/zh-cn/3.7/tutorial/datastructures.html#list-comprehensions" rel="external nofollow noreferrer">https://docs.python.org/zh-cn/3.7/tutorial/datastructures.html#list-comprehensions

标签: # python

留言评论

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~