花木兰

菜鸟的自我成长

python内置函数之列表
#list.append()与list.extend()的区别
list1=['apple','banana','pearl','peanut','banana']
list2=['apple','banana','pearl','peanut','banana']
list3=[1,2,3,4]
list1.append('orange')
print(list1)
list1.append(list2)
print(list1)
list1.append([1,2,3,4])
print(list1)
list1.append(1)
print(list1)
#['apple', 'banana', 'pearl', 'peanut', 'banana', 'orange', ['apple', 'banana', 'pearl', 'peanut', 'banana'], [1, 2, 3, 4], 1]
c=list1.count('apple')
print(c) #1
c=list1.count(list3)
print(c) #1

list1=['apple','banana','pearl','peanut','banana']
list4=['c',"c++","python"]
list1.append(list4) #['apple', 'banana', 'pearl', 'peanut', 'banana', ['c', 'c++', 'python']]
print(list1)

list1=['apple','banana','pearl','peanut','banana']
list4=['c',"c++","python"] #['apple', 'banana', 'pearl', 'peanut', 'banana', 'c', 'c++', 'python']
list1.extend(list4)
print(list1)

list1 = [1, 2, 4]
list2 = [[12, 6], 123]
list1.extend(list2)
print(list1) #[1, 2, 4, [12, 6], 123]

#说明:extend是把追加的序列的每个元素增加到列表中,而append是把追加的整个序列添加到list末尾

#list.reverse()按顺序反转list中的对象
list1=['apple','banana','pearl','peanut','banana']
list1.append('orange')
print(list1)  #['apple', 'banana', 'pearl', 'peanut', 'banana', 'orange']
list1.reverse()
print(list1)  #['orange', 'banana', 'peanut', 'pearl', 'banana', 'apple']

#list.pop() 从list中删除并返回在给定或者最后所引出的obj
list1=['apple','banana','pearl','peanut','banana']
print(list1.pop()) #banana
print(list1.pop(0)) #apple


#list.insert(index,obj)
list1=['apple','banana','pearl','peanut','banana']
list1.insert(-1,'watermelon') #['apple', 'banana', 'pearl', 'peanut', 'watermelon', 'banana']
print(list1)
list1=['apple','banana','pearl','peanut','banana']
list1.insert(0,'watermelon') #['watermelon', 'apple', 'banana', 'pearl', 'peanut', 'banana']
print(list1)

#list.remove(obj)从list中删除对象obj ,删除第一个找到的对象
list1=['apple','banana','pearl','peanut','banana']
list1.remove('banana')
print(list1) #['apple', 'pearl', 'peanut', 'banana']

#list.sort()
list1=['apple','banana','pearl','peanut','banana']
list1.sort()
print(list1) #['apple', 'banana', 'banana', 'peanut', 'pearl']
list1.sort(reverse=True)
print(list1) #['pearl', 'peanut', 'banana', 'banana', 'apple']



list1=['apple','banana','pearl','peanut','banana','21','33']
print(list1)
list1.sort()
print(list1) #['21', '33', 'apple', 'banana', 'banana', 'peanut', 'pearl']


##*************************\
list1=['apple','banana','pearl','peanut','banana',1,2,3,45,21,'21','33']
print(list1)
list1.sort()
print(list1) #['apple', 'banana', 'banana', 'peanut', 'pearl']

#TypeError: '<' not supported between instances of 'int' and 'str'
阅读更多
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

python内置函数之列表

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭