Python中list的完整用法指南

一、创建Python列表的方法

1)通过list()函数进行创建:

list()
lst = list([1,"number",[1,2,3]])

 2)直接赋值

list = [1,"number",[1,2,3]]

二、访问列表中的值

1)直接用索引访问

与字符串的索引一样,列表索引从 0 开始,第二个索引是 1,依此类推。通过索引列表可以进行截取、组合等操作。用索引来访问list中每一个位置的元素,记得索引是从0开始的:

list()
lst = list([1,"number",[1,2,3]])
print(lst[0],lst[1])
#运行结果:1 number

2)使用切片进行列表的访问

num = [1,2,3,4,5]
print(num[1:4]) 
#左闭右开  可以取到下标为1的值,不能取到下标为4的值
#运行结果 [2, 3, 4]

#指定步长为2
list = [1,"number",[1,2,3],2,3]
print(list[1:4:2])
#运行结果 ['number', 2]

3)循环访问列表中的值

list = [1,"number",[1,2,3]]
for i in list:
    print(i)
'''运行结果
1
number
[1, 2, 3]'''

三、对列表进行更新

1)使用append()函数,往list中追加元素到末尾:

lst1=[1,2,3]
lst1.append(4)
print(lst1)
#运行结果 [1, 2, 3, 4]

2)使用insret()函数,把元素插入到指定的位置:


lst2=list([1,'a',[1,2,3]])
lst2.insert(1, 'number')
print(lst2)
#运行结果 [1, 'number', 'a', [1, 2, 3]]

3)直接用索引对值进行更新:

#将索引为2的值替换为2000
list = ['apple', 'ban', 2022, 2023]
list[2] = 2000
print(list)
#运行结果 ['apple', 'ban', 2000, 2023]

四、删除列表元素

1)使用pop(i)函数,删除指定位置的元素,其中i是索引位置:

list1=[1,'a',[1,2,3]]
list1.pop(2)
#这里指定了下标为2的
print (list1)
#运行结果 [1, 'a']

2)使用del语句:

list1=[1,'a',[1,2,3]]
del list1[2]
#这里指定了下标为2的
print (list1)
#运行结果 [1, 'a']

3)使用remove()函数,删除指定位置的元素:

#方法一
list1 = [1,'a',[1,2,3]]
list1.remove([1,2,3])
print (list1)
#方法二
list1 = [1,'a',[1,2,3]]
list1.remove(list1[2])
print (list1)
#运行结果都是 [1,'a']

4)使用clear()函数清空列表:

list1 = [1,'a',[1,2,3]]
list1.clear()
print (list1)
#运行结果 []

物联沃分享整理
物联沃-IOTWORD物联网 » Python中list的完整用法指南

发表评论