list的增删查改及其排序

'''
#list的增删查改及其排序
#列表的增
list=["hello","Linda",13,"welcome","to","China"]

#list的增
a=list.append("Chichy")#增加字符串
print(list)
b=list.append(123)#增加数字
print(list)
c=list.append([1,2,3,4])#增加列表
print(list)
d=list.append((1,"hi",8))#增加元组
print(list)
e=list.append({1:"one",2:"two"})#增加字典
print(list)


#列表的插入
list=["hello","Linda",13,"welcome","to","China"]
a=list.insert(56,"hi")#在要插入的内容后面写上索引,再把要插入的内容写在后面
print(list)
b=list.insert(1,{1,2,3})
print(list)


list=["hello","Linda",13,"welcome"]
c=list.extend("China")#会把字符串拆解成由字符组成的字符串
print(list)#['hello', 'Linda', 13, 'welcome', 'C', 'h', 'i', 'n', 'a']


d=list.extend([1,2,3])#z这样添加到列表的是数字,int 属于不可迭代对象,而extend需要的是可迭代对象
print(list)


#列表的删  pop 可以按照索引去删,也可以不写索引,但默认删除最后一个
list=["hello","Linda",13,"welcome"]
a=list.pop(2)
print(list)
b=list.pop()
print(list)

>>> list=["hello","Linda",13,"welcome"]
>>> list.pop(1)
'Linda'         #把要删除的元素返回
>>> print(list)
['hello', 13, 'welcome']
>>> list.pop()#要么写一个参数,要么不写,不能写多个参数
'welcome'
>>> print(list)
['hello', 13]


#列表的删 remove 按元素去删除
list=["hello","Linda",13,"welcome"]
a=list.remove("hello")#删除字符串hello,若被删除字符串没有在列表中。则会出错
print(list)



#列表的删 del 可以按照索引去删,也可以用切片去删
list=["hello","Linda",13,"welcome"]
del list[-1]
print(list)
del list[2:]
print(list)
del list[0:]
print(list) 
#result
#['hello', 'Linda', 13]
#['hello', 'Linda']
#[]



#列表的清空 clear clear不需要参数
list=["hello","Linda",13,"welcome"]
a=list.clear()
print(list)#[]



#列表的查
list=["hello","Linda",13,"welcome"]
print(list[0:])#查看列表中的元素
for i in list:
    print(i)



#列表的改
list=["hello","Linda",13,"welcome"]
list[0]="Hello"
print(list)#['Hello', 'Linda', 13, 'welcome']
list[0:2]="Good" #若需要给两个元素,你只给了一个,那么将会把第一个元素拆解成都单个字符组成的字符串
print(list)#['G', 'o', 'o', 'd', 13, 'welcome']

list=["hello","Linda",13,"welcome"]
list[0:2]="GOOD","smart"
print(list)#['GOOD', 'smart', 13, 'welcome']

#####列表中只有index,而字符串中有find 和index,find返回查找元素的索引,没有
###查找到就返回-1,而index查找不到就报错。




#列表的排序
#sort 把例表里面的数按照从小到大的顺序排序
a=[1,4,2,6,3,5]
#a1=a.sort(reverse=False) #与a.sort()等价
a1=a.sort()#[1, 2, 3, 4, 5, 6]
print(a)

#sort(reverse=True) 把列表里面的数字从大到小排序
a2=a.sort(reverse=True)
print(a)#[6, 5, 4, 3, 2, 1]

#reverse() 把列表里面的数字的排序恢复成一开始的序列
a3=a.reverse()
print(a)#[1, 2, 3, 4, 5, 6]

猜你喜欢

转载自www.cnblogs.com/GZ1215-228513-Chichy/p/11286044.html