Python列表

Python中常用的序列结构有列表、元组、字典、字符串、集合以及range对象等。
除了字典和集合属于无序序列之外,列表、元组、字符串等序列都支持双向索引,
第一个元素下标为0,第二个元素下标为1,以此类推;
最后一个元素下标为-1,倒数第二个元素下标是-2,以此类推。

列表

列表中的元素占用有序连续内存空间,向Java中的ArrayList。
同一个列表中元素的数据类型可以各不相同。
对于列表、集合、字典等可变序列类型而言,以列表为例,列表中包含的是元素值的内存地址,而不是直接包含元素值。如,

>>> a = [1,2,3]
>>> b = [3,2,1]
>>> id(a[0]) == id(b[2])
True

创建列表

  1. 创建一个普通列表
  2. 创建一个混合列表
  3. 创建一个空列表
>>> num = [1,2,3]
>>> num
[1, 2, 3]

>>> list = [1,'aaa',[2,3]]  #创建混合列表
>>> list
[1, 'aaa', [2, 3]]

>>> empty = []
>>> empty
[]

列表对象常用方法:

list.append(x)
list.extend(L)
list.insert(index,x)
list.remove(x)
list.pop([index])
list.clear()
list.index(x)
list.count(x)
list.reverse()
list.sort()
list.copy()

向列表添加元素

append(element)         #只能添加一个元素
extend(list2)           #添加一个列表
insert(index,element)   #在index索引出插入element元素
>>> char = ['aaa','bbb']
>>> char.append('ccc')
>>> char
['aaa', 'bbb', 'ccc']

>>> char1 = ['eee','fff']
>>> char.extend(char1)
>>> char
['aaa', 'bbb', 'ccc', 'eee', 'fff']
>>> char.insert(3,"ddd")
>>> char
['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff']

>>> len(char)
6

从列表中删除元素

remove(var)
del names[1]    #是一条语句,不是函数
pop             #列表的数据结构是栈,弹出栈顶元素并返回
>>>academy = ['计算机','外语','材料','生命科学','信息']
>>>academy.remove('材料')
>>>academy
['计算机', '外语', '生命科学', '信息']

del academy[3]
>>>academy
>>>['计算机', '外语', '生命科学']

>>>del academy #将会删除整个列表,该列表将不存在,并不是空列表

>>> academy
['计算机', '外语', '生命科学']
>>> name = academy.pop(2)
>>> name
'生命科学'
>>> academy
['计算机', '外语']

列表分片(切片)Slice

一次性从列表中获取多个元素,可以用作拷贝操作。

>>> academy
['计算机', '外语', '机械']
>>> academy[0:2]
['计算机', '外语']

>>> academy[:2]
['计算机', '外语']
>>> academy[1:]
['外语', '机械']
>>> academy[:]
['计算机', '外语', '机械']

拷贝

bak = academy[:]  #bak 和 academy占用不同的空间,互不干扰
bak_1 = academy   #bak_1 和 academy 引用同一个列表,值相同

列表的一些常用操作符

  • 比较操作符
  • 逻辑操作符
  • 连接操作符
  • 重复操作符
  • 成员关系操作符

1.比较操作符

>>> list1 = [1,2]
>>> list2 = [2,1]
>>> list1 > list2   #按字典序列比较
False

2.逻辑操作符

>>> list3 = [1,2]
>>> (list1 < list2) and (list1 == list3)
True
>>> 

3.连接操作符

>>> list4 = list1 + list2
>>> list4
[1, 2, 2, 1]
>>> list4 = list1 + '3'  #加号两边的类型是一致的
#TypeError: can only concatenate list (not "str") to list

4.重复操作符

>>> list1 * 3
[1, 2, 1, 2, 1, 2]
>>> list1 = list1 * 3
>>> list1
[1, 2, 1, 2, 1, 2]

5.成员关系操作符

>>> list = ['aaa','bbb',['ccc','ddd']]
>>> 'aaa' not in list
False
>>> 'ccc' in list
False
>>> 'ccc' in list[2]
True
>>> list[2][1]
'ddd'

列表的其他函数

dir(list)
['__add__', '__class__', '__contains__', '__delattr__', 
'__delitem__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', 
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', 
'__setitem__', '__sizeof__', '__str__', 
'__subclasshook__', 'append', 'clear', 'copy', 'count', 
'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 
'sort']

count #列表元素出现次数
index #列表中某元素第一次出现的下标

>>> list
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> list.count(1)  #统计元素1出现的次数
3


>>> list.index(2) 
1
>>> list.index(1,1) #从下标为1处开始索引
3

>>> list.index(1,1,3) #当索引值不在列表中将会抛出异常
# list.index(1,1,3)
# ValueError: 1 is not in list

reverse #反转列表中元素

>>> list.reverse()
>>> list
[3, 2, 1, 3, 2, 1, 3, 2, 1]

sort #对列表元素排序,默认为升序

>>> list.sort()
>>> list
[1, 1, 1, 2, 2, 2, 3, 3, 3]

>>> list.reverse()
>>> list
[3, 3, 3, 2, 2, 2, 1, 1, 1]

比较list.reverse()和reversed(list)

list.reverse():在本地逆序操作
reversed(list):不对原列表做任何修改
同理,list.sort()和sorted()与其一样。

>>> aList = list(range(1,10,2))
>>> aList
[1, 3, 5, 7, 9]
>>> newList = reversed(aList)
>>> newList
<list_reverseiterator object at 0x023BC210>
>>> aList
[1, 3, 5, 7, 9]
>>> list(newList)
[9, 7, 5, 3, 1]

sort(func,key)#默认是归并排序
sort(reverse = False)#参数默认值为False,等价于sort()
sort(reverse = True)

>>> list.sort(reverse = False) #等价于list.sort()
>>> list
[1, 1, 1, 2, 2, 2, 3, 3, 3]

>>> list.sort(reverse = True)
>>> list
[3, 3, 3, 2, 2, 2, 1, 1, 1]

比较两种遍历:

>>> aList = [1] * 12
>>> aList
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> for temp in aList:
    if temp == 1:
        aList.remove(temp)
>>> aList
[1, 1, 1, 1, 1, 1]
>>> bList = [1] * 12
>>> bList
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> for temp in bList[::-1]:    #-1表示从右开始遍历,步长为1
    if temp == 1:
        bList.remove(temp)  
>>> bList
[]

逆序遍历列表

>>> cList = list(range(10,20,2))
>>> cList
[10, 12, 14, 16, 18]
>>> cList[::-1]
[18, 16, 14, 12, 10]

>>> dList = cList
>>> dList is cList
True

序列操作的常用内置函数

cmp(list1,list2)
len(list)
max(list)
min(list)
#说明:max和min返回列表中的最大或最小元素,同样适用于元组、字符串、集合、range对象和字典等。
#但对字典操作时,默认是对字典的"键"进行计算,如果需要对字典的"值"进行计算,用字典对象的values()方法
sum(list)
zip(list1,list2)
        >>> aList = [1,2,3]
        >>> bList = [4,5,6]
        >>> cList = [7,8,9]
        >>> dList = zip(aList,bList,cList)
        >>> dList
        <zip object at 0x023F6D28>
        >>> dList = list(dList)
        >>> dList
        [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
enumerate(list):
#枚举列表、元组或其他可迭代对象的元素,返回枚举对象,枚举对象中每个元素是包含下标和元素值的元组。
#该函数对字符串和字典同样有效,但对字典操作时区分"键"和"值"。
        >>> dList
        [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        >>> for item in enumerate(dList):
            print(item)
        (0, (1, 4, 7))
        (1, (2, 5, 8))
        (2, (3, 6, 9))

        >>> for index,ch in enumerate('ABC'):
            print((index,ch),end=',')
        (0, 'A'),(1, 'B'),(2, 'C'),

        >>> a = {'A':65,'B':66,'C':67}
        >>> a
        {'B': 66, 'C': 67, 'A': 65}
        >>> for i,v in enumerate(a):
            print(i,v)
        0 B
        1 C
        2 A

        >>> for i,v in enumerate(a.values()):
            print(i,v)
        0 66
        1 67
        2 65
        >>> 

列表推倒式

>>> aList = [x**2 for x in range(1,10,2)]
>>> aList
[1, 9, 25, 49, 81]

等价于

>>> aList =[]
>>> for x in range(1,10,2):
    aList.append(x**2)
>>> aList
[1, 9, 25, 49, 81]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值