python列表与元组

目录

查询及切片

删除

添加

修改

反转

拼接

排序

复制

元组


 


查询及切片

#初始值
list1 = ["a","b","c","d","e","f","g"]
print(list1[0])
#a
print(list1[2:5])
#['c', 'd', 'e']
print(list1[0:-3])
#['a', 'b', 'c', 'd']
print(list1[:3])
#['a', 'b', 'c']
print(list1[-5:-1])
#['c', 'd', 'e', 'f']
print(list1[-5:])
#['c', 'd', 'e', 'f', 'g']
print(list1[1:6:2])
#['b', 'd', 'f']
print(list1.index("c"))
#2
print(list1.count("c"))
#1

删除

#初始值list1 = ["a","b","c","d","e","f","g"]
print(list1.pop())
#g
print(list1)
#['a', 'b', 'c', 'd', 'e', 'f']
print(list1.pop(3))
#d
print(list1)
#['a', 'b', 'c', 'e', 'f']
list1.remove("c")
print(list1)
#['a', 'b', 'e', 'f']
del list1[1]
print(list1)
#['a', 'e', 'f']

添加

#初始值['a', 'e', 'f']
list1.append("h")
print(list1)
#['a', 'e', 'f', 'h']
list1.insert(2,"i")
print(list1)
#['a', 'e', 'i', 'f', 'h']
#修改
list1[1] = "j"
print(list1)
#['a', 'j', 'i', 'f', 'h']

修改

#初始值['a', 'e', 'i', 'f', 'h']
list1[1] = "j"
print(list1)
#['a', 'j', 'i', 'f', 'h']

反转

#初始值['a', 'j', 'i', 'f', 'h']
list1.reverse()
print(list1)
#['h', 'f', 'i', 'j', 'a']

拼接

#初始值list1 = ['h', 'f', 'i', 'j', 'a']
list2 = ["1","2","3"]
list1.extend(list2)
print(list1)
print(list2)
#['h', 'f', 'i', 'j', 'a', '1', '2', '3']
#['1', '2', '3']

排序

#初始值['h', 'f', 'i', 'j', 'a', '1', '2', '3']
#排序
#list.sort(cmp=None, key=None, reverse=False)
'''
cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
'''
list1.sort()
print(list1)
#['1', '2', '3', 'a', 'f', 'h', 'i', 'j']
list1.sort(reverse=True)
print(list1)
#['j', 'i', 'h', 'f', 'a', '3', '2', '1']

复制

#浅copy
list3 = ["a","b",["c","d"],"e"]
list4 = list3.copy()
print(list3)
print(list4)
#['a', 'b', ['c', 'd'], 'e']
#['a', 'b', ['c', 'd'], 'e']
list3[0] = "f"
print(list3)
print(list4)
#['f', 'b', ['c', 'd'], 'e']
#['a', 'b', ['c', 'd'], 'e']
list3[2][0] = "g"
print(list3)
print(list4)
#['f', 'b', ['g', 'd'], 'e']
#['a', 'b', ['g', 'd'], 'e']


list3 = ["a","b",["c","d"],"e"]
list4 = list3
print(list3)
print(list4)
#['a', 'b', ['c', 'd'], 'e']
#['a', 'b', ['c', 'd'], 'e']
list3[0] = "f"
print(list3)
print(list4)
#['f', 'b', ['c', 'd'], 'e']
#['f', 'b', ['c', 'd'], 'e']
list3[2][0] = "g"
print(list3)
print(list4)
#['f', 'b', ['g', 'd'], 'e']
#['f', 'b', ['g', 'd'], 'e']

元组

#元组不可修改,只能查询
list5 = ("1","2","3")

猜你喜欢

转载自blog.csdn.net/sinat_23110321/article/details/81152220