码迷,mamicode.com
首页 > 编程语言 > 详细

Python之list列表方法详解

时间:2018-03-17 21:44:13      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:扩展   ####   key   sel   append   .so   指定位置   art   修改   

列表是有序的,元素可以被修改

test = [11, 22, 33, 44, 55, 22]

################################## List 列表之删除元素 ##################################### del test[1] 切片删除
# del test[1:4] 删除test[1] ,test[2],test[3]
# clear方法,清空test列表中的所有元素,变为空列表 test[]
# test.clear()

# pop方法,弹出test列表指定位置的元素,弹出的元素可以用变量接收
# pop(self, index=None) 参数:index:待弹出元素的下标(可以为空,为空时默认弹出列表最后一个元素)
# v = test.pop(1)

# remove方法,删除(默认从左往右删除第一个符合要求的value,后面符合要求的value不删除)
# remove(self, value) 参数:value:待删除元素
# test.remove(22)

################################## List 列表之增加元素 ####################################

# append方法,在test列表末尾增加一个元素
# append(self, p_object) 参数:p_object:待添加的元素
# test.append(66)
# test.append([77, 88])

# extend方法,扩展test列表 extend(self, iterable) iterable:传入可迭代对象(例如:传入列表,字符串等)
# test.extend([11, ‘22‘])
# extend和append区别如下:
# test.extend([11, ‘22‘]) --> [11, 22, 33, 44, 55, 11, ‘22‘]
# test.extend(‘abcd‘) --> [11, 22, 33, 44, 55, ‘a‘, ‘b‘, ‘c‘, ‘d‘]
# test.append([11, ‘22‘]) --> [11, 22, 33, 44, 55, [11, ‘22‘]]
# test.append(‘abcd‘) --> [11, 22, 33, 44, 55, ‘abcd‘]

# insert方法,在test列表指定位置插入元素
# insert(self, index, p_object) 参数:index:指定下标位置插入(下标前面插入) p_object:待插入元素
# test.insert(1, ‘551‘)

################################## List 列表之查找 ####################################
# index方法,查找元素索引位置(例如:test1 = [11,22,33,22] test.index(22)从左往右找到找到第一个22就停止后面的22就不找了)
# index(self, value, start=None, stop=None) 参数 vale:待查找下标的元素 start:从哪个下标开始查找 stop:寻找结束的下标(查找时不查找结束的下标)
# v = test.index(22, 0, 2) # --> 返回 1

################################## List 列表之其他 ####################################
# copy方法,浅拷贝test列表
# v = test.copy()

# count方法,计算test列表中指定元素出现的次数
# count(self, value) 参数:value:待计算的元素
# v1 = test.count(22)

# reverse方法,test列表反转
# test.reverse()

# sort方法,对test列表内元素进行排序
# sort(self, key=None, reverse=False)参数:reverse:False时从小到大排序,True时从大到小排序
# test.sort(reverse=True)
print(test)

Python之list列表方法详解

标签:扩展   ####   key   sel   append   .so   指定位置   art   修改   

原文地址:https://www.cnblogs.com/suendanny/p/8592468.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!