Python 之 list

python之list 常用操作

参考地址

http://c.biancheng.net/view/2208.html

append

list_container.append("last")                # 添加 作为一个元素添加到末尾  [0, 1, 2, 'last',]
list_container.append([1,2,3])               # 添加 作为一个元素添加到末尾  [0, 1, 2, 'last', [1, 2, 3],]
list_container.append(list_container_1)
print(list_container)

insert

list_container.insert(0,"insert first")   # insert 新增  到指定位置                      ['insert first', 0, 1, 2, 'append']
list_container.insert(100,"insert last")  # insert新增 指定位置不存在,新增到末尾       [ 0, 1, 2, 'append', 'insert last']

extend

lint_container_1=[11,22,33]
lint_container.extend(lint_container_1)   # extend 两个列表合并  [0, 1, 2, 11, 22, 33]

append多用于把元素作为一个整体插入
insert多用于固定位置插入
extend多用于list中多项分别插入

del 根据索引删除元素  (命令)

del list_name[list_index]

lint_container_1=[1,2,3,"hello","sing"]
del lint_container_1[1]                     # del 删除 指定index (正序) [1, 3, 'hello', 'sing']
del lint_container_1[-1]                    # del 删除 指定index(倒叙)

del lint_container_1[start_index:end_index] # del 连续删除指定长度
del del lint_container_1[-5:-2]             # 取头不取尾

pop 根据索引删除元素 (方法)

list_name.pop(list_index)

return_value = lint_container_1.pop(3)       # pop 删除 指定index ,有返回值 返回pop出列表的元素  [1, 2, 3]
print(return_value)                        # hello

remove  根据元素值删除元素(方法)

lint_container_1=[1,2,3,"hello","sing"]
lint_container_1.remove("hello")
list_container_1=[1,2,3,"helloll","sing"]
list_container_1.remove("helollooooooooooooo")  # 如果移除的目标元素不存在,程序回报错

if "hello" in list_container_1:    # remove 移除列表元素前,先判断列表中是否存在目标元素
	list_container_1.remove("hello")
else:
	print("hello not in list_container")

clear 清空 (方法)

lint_container_1=[1,2,3,"helloll","sing"]
lint_container_1.clear()
print(lint_container_1)

 

修改 

直接赋值 f[i]=5

list_container=[0,1,2]
for i in range(len(list_container)):
    if list_container[i]==2:
        list_container[i]=3
    else:
        pass
    print(list_container)

查找

index()方法,根据元素查找到元素所在索引位置

index_1=list_container.index(0,0,6)   # list_name.index(需查找的元素,索引开始,索引结束)   输出结果为 0 元素的索引位置

count()方法   统计元素出现次数

print(list_container.count(333))        # 统计元素出现的次数

其他

list_name.reverse()  # 列表反转

list_container.sort() # 排序

切片      list_name[first:end:len]

list_container=[0,1,2,3,4,5,6,7,8,9]
list_container_1=list_container[5:9:2] # [5, 1, 1, 333]
list_container_2=list_container[-6:] # [4, 5, 6, 7, 8, 9]









原文地址:https://www.cnblogs.com/hellosecretgarden/p/15439226.html