python中的列表与C/C++中的数组相似。
一般定义方式:list_name=[element1,element2…]
element可以是字符串、数字、字符(包括汉字)、变量、列表(一维或多维)等。列表具有索index,从0开始,可以直接通过list_name[index][index]…来获得多维列表中的元素。
特点与list列表相似,但不可修改。
list与tuple方法list方法:
# edited by Lyu
# 仅供学习使用,禁止一切商业用途
name=["Lyu Zhiyu","Chen Xiao","Liu Yu"] #list contanin 3 elements
name2=[1,2,3,4]
print(name[0:2])
print(name[ :2]) #print name[0] and name[1]
print(name[-3:-1]) #print name[0] and name[1]
print(name[-2: ]) #print name[2] and name[3]
#add
name.append("Liu Ge") #insert to the end
print(name[-2: ]) #changed
name.insert(0,"Hao Yuan") #insert to the int :0
print(name[ :2]) #changed
#change
name[0]="Yu San" #change name[0] as Yu San
#delete
name.remove("Chen Xiao") #remove name
del name[0] #delete name
name.pop() #delete the last by default
name.pop(0) #delete the int :0
#find the index
print(name.index("Liu Yu"))
#count
print(name.count("Liu Yu"))
#reverse
name.reverse()
#sort
name.sort()
#clear
#name.clear()
#extend
name.extend(name2)
print(name)
tuple方法:
# edited by Lyu
# 仅供学习使用,禁止一切商业用途
#tuple is unchangeable
#index
#count
深浅复制
*此处列举一些应当注意的问题
notes:
# edited by Lyu
# 仅供学习使用,禁止一切商业用途
import copy
name=["Lyu Zhiyu","Chen Xiao","Liu Yu"] #list contanin 3 elements
name2=["Lyu Zhiyu","Chen Xiao","Liu Yu",[1,2,3]]
#label,name3=name if name changed,name3 changed too.
name3=name
print(name,'\n',name3)
name[0]="LZY"
print(name,'\n',name3,'\n')
#sallow copy
'''
four methods
1:
name3=name[:]
2:
name3=name.copy()
3.
name3=copy.copy(name)
4.
name3=list(name)
'''
name3=name.copy()
name4=name2.copy()
print(name,"\n",name3)
print(name2,"\n",name4)
name.pop()
del name2[3][0]
print(name,"\n",name3)
print(name2,"\n",name4,'\n')
#deep copy
name4=copy.deepcopy(name2)
print(name2,"\n",name4)
del name2[3][0]
print(name2,"\n",name4)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)