python 列表(List)

列表是由一系列按特定顺序的元素组成。

列表是有序集合,当我们需要访问列表中的某一元素时,只需要将该元素的位置或索引告诉python即可,第一个索引是从0开始,依次类推

在python中,用来表示列表,并用逗号来分隔其中的元素

1.列表常用的独有的方法

(1)append()方法

方法/参数 备注
方法:append( “content" ) 在列表后面添加元素
参数:content 需要插入的元素
list = []
list.append( "Maple" )
list.append( "yf" )
list.append( "hao" )
print(list)

#输出的结果如下:
['Maple', 'yf', 'hao']

(2)insert()方法

方法/参数 备注
方法:insert( index, content ) 在index前插入指定的元素(content)
参数:index 需要在哪个索引的位置
参数:content 需要插入的元素
list = ["Maple", "yf", "hao","123"]

list.insert(2,"study")

print(list)

#输出的结果如下:
['Maple', 'yf', 'study', 'hao', '123']

(3)pop()方法

方法/参数 备注
方法:pop( [index] ) 将指定索引位置的元素删除,并返回删除元素的值
不指定索引位置,默认从删除列表最后一个元素
参数:index 元素的索引位置
list = ["Maple", "yf", "hao","123"]

list.pop(1)

print(list)

#输出的结果如下:
['Maple', 'hao', '123']

(4)remove()方法

参数/方法 备注
方法:remove( "content" ) 将指定的元素删除
参数:content 元素的值
list = ["Maple", "yf", "hao","123"]

list.remove( "hao" )

print(list)

#输出的结果如下:
['Maple', 'yf', '123']

(5)clear()方法

参数/方法 备注
clear() 将列表的内容清空
list = ["Maple", "yf", "hao","123"]

list.clear()

print(list)

#输出的结果如下:
[]

2.公共方法

(1)len方法

len()方法:可以用来获得列表有几个元素

list = ["Maple", "yf", "hao","123"]

print( len(list) )

#输出的结果如下:
4

(2)切片

用于获取指定的元素或多个元素

list = ["Maple", "yf", "hao","123"]

print( list[0:2] )

#输出的结果如下:
['Maple', 'yf']

(3)索引

获取指定的索引的元素

list = ["Maple", "yf", "hao","123"]

print( list[2] )

#输出的结果如下:
hao

(4)del删除

删除指定元素

list = ["Maple", "yf", "hao","123"]

del list[2]

print( list )

#输出的结果如下:
['Maple', 'yf', '123']

(5)步长

list = ["Maple", "yf", "hao","123"]

print( list[0:2:2])

#输出的结果如下:
['Maple']

(6)修改

list = ["Maple", "yf", "hao","123"]

list[2] = "您好"

print(list)

#输出的结果如下:
['Maple', 'yf', '您好', '123']

(7)for循环

list = ["Maple", "yf", "hao","123"]

for item in list:
    print(item)
    
#输出的结果如下:
Maple
yf
hao
123
posted on 2020-06-26 21:34  杨枫哥  阅读(464)  评论(0编辑  收藏  举报