python中的列表

列表

 

1.列表是python中内置有序,可变序列,列表的所有元素放在一对中括号中'[]',并使","隔开;

 

 

2.当列表元素增加或者删除时,列表中的元素自动进行扩展或收缩

 

 

3.列表中的元素数据类型,可以为各种类型,如整数,字符串,浮点数,还可以是列表,元祖,字典,集合及其它自定义类型的对象

  TestList = [{'name':'mh','age':'28','sex':'男'},[1,2.9,(1,2,3,4,5),'我是一个字符串'],'我是最后一个元素']

 

4.列表常规操作

  访问列表元素 

print('TestList[0]:',TestList[0])
输出:
TestList[0]: {'age': '28', 'name': 'mh', 'sex': ''}

TestList1 = [1,2,3,4,5,6,7,8]
print(TestList1[2:7])#范围取值,顾头不顾尾(以下标区分)
输出:
[3, 4, 5, 6, 7]

  更新列表

print(TestList[2])
TestList[2]=('','','','','','')
print(TestList[2])

输出:
我是最后一个元素
('', '', '', '', '', '')

  删除列表元素,可以使用 del 语句来删除列表的的元素

print(TestList)
del TestList[2]
print(TestList)

输出:
[{'name': 'mh', 'age': '28', 'sex': ''}, [1, 2.9, (1, 2, 3, 4, 5), '我是一个字符串'], ('', '', '', '', '', '')]
[{'name': 'mh', 'age': '28', 'sex': ''}, [1, 2.9, (1, 2, 3, 4, 5), '我是一个字符串']]

  下标反向取值

TestList1 = [1,2,3,4,5,6,7,8]
print(TestList1[-6])#从右往左开始下标为-1,-2,-3......

输出:
3

5.列表常用函数与方法

  返回列表长度,列表元素个数len(listname)

TestList1 = [1,2,3,4,5,6,7,8]
print(len(TestList1))

输出:
8

  元组转为列表list(tuple)

tuple = ('a','b','c','d')
print(list(tuple))

输出:
['a', 'b', 'c', 'd']

  末尾添加新的元素 list.append(x)

TestList1 = [1,2,3,4,5,6,7,8]
TestList1.append(9)
print(TestList1)

输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

  统计某个元素在列表中出现的次数 list.count(x)

TestList1 = [1,2,3,4,5,6,7,8,8]
print(TestList1.count(8))

输出:
2

  在列表末尾追加另一个列表 list.extend(list)

TestList = [{'name':'mh','age':'28','sex':''},[1,2.9,(1,2,3,4,5),'我是一个字符串'],'我是最后一个元素']
TestList1 = [1,2,3,4,5,6,7,8,8]
TestList1.extend(TestList)
print(TestList1)

输出:
[1, 2, 3, 4, 5, 6, 7, 8, 8, {'name': 'mh', 'sex': '', 'age': '28'}, [1, 2.9, (1, 2, 3, 4, 5), '我是一个字符串'], '我是最后一个元素']

  从列表中找出某个值第一个匹配的索引位置 list.index(obj)

TestList1 = [1,2,3,4,5,6,7,8,8]
print(TestList1.index(8))

输出:
7

  将对象插入列表,如果下标不存在,则元素追加到最后list.insert(index,x)

TestList1 = [1,2,3,4,5,6,7,8,8]
TestList1.insert(1,9)
TestList1.insert(20,10)
print(TestList1)

输出:
[1, 9, 2, 3, 4, 5, 6, 7, 8, 8, 10]

  移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 list.pop(index)

TestList1 = [1,2,3,4,5,6,7,8,8,10]
TestList1.pop()#不指定下标的情况下,默认删除最后一个
print(TestList1)

输出:
[1, 2, 3, 4, 5, 6, 7, 8, 8]

  移除列表中某个值的第一个匹配项,list.remove(obj)

TestList1 = [1,2,3,4,5,6,7,8,8,10]
TestList1.remove(10)
print(TestList1)

输出:
[1, 2, 3, 4, 5, 6, 7, 8, 8]

  反向列表中元素,list.reverse()

TestList1 = [1,2,3,4,5,6,7,8,8,10]
TestList1.reverse()
print(TestList1)

输出:
[10, 8, 8, 7, 6, 5, 4, 3, 2, 1]

  列表排序,list.sort()

TestList1 = [1,2,3,4,5,6,7,8,8,1,12,5,99,43]
TestList1.sort()
print(TestList1)

输出:
[1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 12, 43, 99]

  清空列表,list.clear()

TestList1 = [1,2,3,4,5,6,7,8,8,1,12,5,99,43]
TestList1.clear()
print(TestList1)

输出:
[]

 

 

  

 

    

  

  

    

 

  

 

 

posted @ 2019-09-10 17:19  小马哥007  阅读(590)  评论(0编辑  收藏  举报