侧边栏壁纸
  • 累计撰写 197 篇文章
  • 累计收到 496 条评论

Python学习笔记之列表操作

2019-9-21 / 0 评论 / 60 阅读
# 列表的相关函数
'''
list.append()
    功能: 在列表的末尾添加一个元素
    格式: 列表.append(值)
    返回值: None
    注意: 直接操作原有列表没有返回值
'''

'''
list.insert(索引,值)
    功能: 在指定索引之前插入数据
    格式: 列表.insert(值)
    返回值: None
    注意: 直接操作原有列表没有返回值
'''
listvar = [1,2,3,4,5,6]
listvar.insert(1,'hello')
print(listvar) # [1, 'hello', 2, 3, 4, 5, 6]

'''
list.extend()
    功能: 将一个列表继承给另一个列表
    格式: list.extend(序列)
    返回值: None
    注意: 直接操作原有列表没有返回值
'''
list2 = [11,22,33]
list2.extend(listvar)
print(list2) # [11, 22, 33, 1, 'hello', 2, 3, 4, 5, 6]

'''
list.pop()
    功能:通过索引弹出一个元素
    格式:list.pop(索引)
    返回值:被删除的值
    注意:直接操作原有列表 返回值是被删除的值
'''
res = list2.pop()
print(list2) # [11, 22, 33, 1, 'hello', 2, 3, 4, 5]
list2.pop(3)
print(list2) # [11, 22, 33, 'hello', 2, 3, 4, 5]

'''
list.remove()
    功能: 通过给予的值来删除,如果多个相同元素,默认删除第一个
    格式: list.remove(值)
    返回值: 无
    注意: 如果有索引的话推荐使用pop,pop效率比remove高,但remove可以删除无序容器的值
'''
setvar = {1,2,3,3,2,1,'hello','world'}
print(setvar) # {1, 2, 3, 'hello', 'world'}
setvar.remove('hello') 
print(setvar) # {1, 2, 3, 'world'}

# 深拷贝 和 浅拷贝
# example 浅拷贝
listvar = [1,2,3,4,5,6]
listvar2 = listvar
listvar.append(7)
print(listvar2) # [1, 2, 3, 4, 5, 6, 7]

# 使用copy
# copy 拷贝顶级中的list
import copy
# copy.copy()
listvar = [1,2,3,4,5]
listvar2 = listvar.copy()
listvar.append(6)
print(listvar2) # [1, 2, 3, 4, 5]

listvar = [1,2,3,[4,5,6]]
listvar2 = copy.copy(listvar)
listvar.append(3)
print(listvar2)

# 深拷贝
import copy
listvar = [1,2,3,4,5,[6,7,8]]
listvar2 = copy.deepcopy(listvar)
listvar[-1].append(8)
print(listvar2)

评论一下?

OωO
取消