Python——列表、字典等容器类型全搞定!

本文深入探讨了Python中的列表数据结构,包括创建、访问、修改和操作列表的方法,如切片、append、insert、extend等。此外,还介绍了列表在实现堆栈、队列中的角色,以及列表与元组、字典和集合的区别和应用场景。同时,讨论了字典的哈希实现原理和操作,如添加、查找和删除元素。最后,涉及到了集合的特性及运算,如交集、并集、差集和补集。

   列表定义

     列表是处理一组有序项目的数据结构;列表是python中最具灵活性的有序集合对象类型;列表可以包含任何类型的对象:字符串、数字甚至其他列表(任何数据类型);列表是可变的数据类型,即这种类型的值是可以被修改的。

     lst = []

     lst2 = list()

     下标切片:【start;end;step】       

>>> lst2 = list("abc")

>>> lst2

['a', 'b', 'c']

>>> lst2[0]

'a'

>>> lst2[2]

'c'
>>> lst = ["a","b","c","d","e"]

>>> lst

['a', 'b', 'c', 'd', 'e']

>>> lst[-3:1:-2]

['c']

>>> lst = ["a",10,1.1,print,input,None]

>>> lst[3]

<built-in function print>

>>> lst = ["a",10,1.1,print(),input,None]

>>> lst[3]

>>> print(lst[3])

None

  列表的增加

nsert、extend(扩展增加,可迭代对象)、append(加一个)

>>> lst = [1,2,3,4,5]

>>> lst.append(13)

>>> lst

[1, 2, 3, 4, 5, 13]

>>> lst.insert(1,"taylor")

>>> lst

[1, 'taylor', 2, 3, 4, 5, 13]

>>> lst.extend([1,3])

>>> lst

[1, 'taylor', 2, 3, 4, 5, 13, 1, 3]

  拓展    

1.字典的实现原理

如何增加内容,如何查找内容

hash()

2.堆栈  Stack  : last-in, first-out 后进先出

义列表:

            进入: append()

            出去: pop()

3.队列

用列表实现队列

         列表也可以用作队列,最先加入的元素,最先取出(“先进先出”);然而,列表作为队列的效率很低。因为,在列表末尾添加和删除元素非常快,但在列表开头插入或移除元素却很慢(因为所有其他元素都必须移动一位)。

         实现队列最好用 collections.deque,可以快速从两端添加或删除元素。例如:

 

         >>>

         >>> from collections import deque

         >>> queue = deque(["Eric", "John", "Michael"])

         >>> queue.append("Terry")           # Terry arrives

         >>> queue.append("Graham")          # Graham arrives

         >>> queue.popleft()                 # The first to arrive now leaves

         'Eric'

         >>> queue.popleft()                 # The second to arrive now leaves

         'John'

         >>> queue                           # Remaining queue in order of arrival

         deque(['Michael', 'Terry', 'Graham'])

        =====

         >>> singer

         ['cali', 'liuzhiwen', 'hejin', 'zhujiahui']

         >>> singer.pop(1)

         'liuzhiwen'

         >>> singer

         ['cali', 'hejin', 'zhujiahui']

         >>> singer.remove()

         Traceback (most recent call last):

         File "<stdin>", line 1, in <module>

         TypeError: remove() takes exactly one argument (0 given)

         >>> singer.remove(1)

         Traceback (most recent call last):

         File "<stdin>", line 1, in <module>

         ValueError: list.remove(x): x not in list

         >>> singer.remove("hejin")

         >>> singer

         ['cali', 'zhujiahui']

         >>>

  总结下pop() remove()的区别     

>>> singer

['cali', 'zhujiahui']

>>> del singer[1]

>>> singer['cali']

>>> import random

>>> random.randint(1,9)

 8

>>> random.randint(1,3)

1

>>>

singer = ["cali",'liu',"wang"]

for i in singer:

        print(i)

singer = ["cali",'liu',"wang"]

 # enumerate 枚举函数 :给列表元素加上编号,编号默认从0开始

for i in enumerate(singer):

         print(i)

for i, j in enumerate(singer):

         print(f"id:{i} name:{j}")

列表的修改

>>> lst = ["a","b","a","c","d"]

>>> lst[3]="f"

>>> lst

['a', 'b', 'a', 'f', 'd']

>>> lst[1:2]

['b']

>>> lst[1:2] = "lzc"

>>> lst

['a', 'l', 'z', 'c', 'a', 'f', 'd']

>>> lst[1:5] = "0"

>>> lst

['a', '0', 'f', 'd']

>>> lst

['a', '0', 'f', 'd']

>>> lst[2:3]

 ['f']

>>> lst[2:2] = "111"

>>> lst

 ['a', '0', '1', '1', '1', 'f', 'd']

>>> lst[::-1]        

['d', 'f', '1', '1', '1', '0', 'a']

>>> lst = ["a","B","c","H"]

>>> lst.sort()

>>> lst

['B', 'H', 'a', 'c']

>>> lst.sort(reverse=True)        

>>> lst

['c', 'a', 'H', 'B']

>>> lst = ["a","B","c","H"]

>>> lst.sort()

>>> lst

['B', 'H', 'a', 'c']

>>> lst.sort(reverse=True)

 >>> lst

['c', 'a', 'H', 'B']

>>> len(lst)

4        

>>> lst = ["1","1","a","aa","a","b"]

>>> len(lst)

6

>>> lst.count("1") #出现次数

2

>>> lst.index("a") #第一次出现的角标

2

>>> for i in enumerate(lst):

...   print(i)

  ...

(0, '1')

(1, '1')

(2, 'a')

(3, 'aa')

(4, 'a')

(5, 'b')

元组

元组与列表的区别

         元组不可变,列表可变类型

字典

        字典是键值映射的数据结构;字典是无序的;是可变数据类型;key必须是唯一的,天生去重,key是可hash对象;value可以是任意值。

字典的实现原理

字典是依靠哈希表(Hash Table)进行实现的,使用开放地址法解决冲突。

数据添加:把key通过哈希函数转换成一个整型数字,然后就将该数字对数组长度进行取余,取余结果就当作数组的下标,将value存储在以该数字为下标的数组空间里。

数据查询:再次使用哈希函数将key转换为对应的数组下标,并定位到数组的位置获取value

    1.怎么查找

    2.为什么key要是可hash对象

    3.为什么key天生去重

增加

        >>> a =   {"taylorswift":"lovestory","张惠妹":"血腥爱情故事"}

        >>> a

        {'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事'}

        >>> a['c'] = 4

        >>> a

        {'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事', 'c': 4}

        >>> a.get('d',0)

        0

        >>> a.get('c',0)

        4

        >>> a

        {'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事', 'c': 4}

删除

        >>> a.pop("c")

        4

        >>> a

        {'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事'}

合并

        >>> a

        {'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事'}

        >>> b

        {'x': 3}

        >>> a.update(b)

        >>> a

        {'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事', 'x': 3}

        >>> a+b

        Traceback (most recent call last):

        File "<stdin>", line 1, in <module>

        TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

    pack和unpack、**:

    dict1 = {"a":1,"b":2},  **dict1 --->a=1,b=2

        a = {"name":"sc","age":18}

        print("my name is {name},age is {age}".format(name="sc",age="18"))

        print("my name is {name},age is {age}".format(**a))

        结果:

        my name is sc,age is 18

        my name is sc,age is 18

成员关系运算符

>>> a

{'taylorswift': 'lovestory', '张惠妹': '血腥爱情故事', 'x': 3}

>>> a in a.values()

False

>>> lovestory in a.values()

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

NameError: name 'lovestory' is not defined

>>> "lovestory" in a.values()

True

>>> 3 in a.values()

True

>>> a.keys()

dict_keys(['taylorswift', '张惠妹', 'x'])

遍历

        >>> for i in a:

        ...   print(i)

        ...

        taylorswift

        张惠妹

        x

        >>> for i in a.items():

        ...   print(i)

        ...

        ('taylorswift', 'lovestory')

        ('张惠妹', '血腥爱情故事')

        ('x', 3)

集合

      只有key的字典,天生去重,无序不重复。

        >>> b = {1,2,2,232,121,12,12,13}

        >>> b

        {1, 2, 232, 12, 13, 121}

查重

        str1 = "eeecedt"

        s1 = set(str1)

        for i in s1:

        print(f"{i}出现了{str1.count(i)}次。")

删除:remove报错,discard不会报错

        >>> a = {'x',1,3,4,5,6,7,7,'wef'}

        >>> a

        {1, 3, 4, 5, 6, 7, 'wef', 'x'}

        >>> a.remove("x")

        >>> a

        {1, 3, 4, 5, 6, 7, 'wef'}

        >>> a.remove(7)

        >>> a

        {1, 3, 4, 5, 6, 'wef'}

        >>> a.discard('5')

        >>> a

        {1, 3, 4, 5, 6, 'wef'}

        >>> a.discard(5)

         >>> a

        {1, 3, 4, 6, 'wef'}

        >>> a.remove('5')

        Traceback (most recent call last):

         File "<stdin>", line 1, in <module>

        KeyError: '5'

集合的运算:交&并|补^

        >>> s1 = {1,2,3,4,5,6,}

        >>> s2 = {1,2,3,324,543,63}

        >>> s1 & s2

        {1, 2, 3}

        >>> s1 - s2

        {4, 5, 6}

        >>> s2 - s1

        {324, 543, 63}

        >>> s1 | s2

        {1, 2, 3, 4, 5, 6, 324, 543, 63}

        >>> s1 ^ s2

        {324, 4, 5, 6, 543, 63}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chaochao️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值