Python 学习笔记(3)——元组和字典

    xiaoxiao2022-06-29  42

    二、元组

    >> 元组是不可变的,使用()创建。

    元组可以作为字典的键,并且函数的参数是以元组的形式传递的。

    创建元组的时候,每个元素的后面都需要跟着一个逗号,即使只有一个元素也不例外,超过一个元素时候,最后一个逗号可以省略。例如:

    et=() et=('abc',) et Out[43]: ('abc',) el=('abc','dfg','dada')

    >> 元组解包

    a,b,c=el a Out[46]: 'abc' b Out[47]: 'dfg' c Out[48]: 'dada'

    三、字典

            元组的元素不是按照偏移量0,1,2....等来访问的,而是通过每个元素与之对应的键来访问的,键通常是字符串,也可以是其他任意的类型,布尔型、整型、元组、字符串等等。字典是可以改变的,字典的顺序是不重要的。

            使用{}创建字典。dict()转换为字典类型。每个子序列的第一个元素作为键,第二个元素作为值。

    lol=[['a','b'],['c','d'],['e','f']] dict(lol) Out[50]: {'a': 'b', 'c': 'd', 'e': 'f'}

    >>通过键改变字典的值

    lols Out[53]: {'a': 'b', 'c': 'd', 'e': 'f'} lols['a']='League' lols Out[55]: {'a': 'League', 'c': 'd', 'e': 'f'} lols['c']='of' lols['e']='Legends' lols Out[58]: {'a': 'League', 'c': 'of', 'e': 'Legends'}

    >> update() 函数合并两个字典

    h={'l':'o','h':'m'} lols.update(h) lols Out[61]: {'a': 'League', 'c': 'of', 'e': 'Legends', 'h': 'm', 'l': 'o'}

    >> del() 删除特定元素

    del lols['h'] lols Out[63]: {'a': 'League', 'c': 'of', 'e': 'Legends', 'l': 'o'} >> in判断是否子字典中

    >>clear() 删除所有元素

    lols.clear() lols Out[65]: {}

    >>获取元素

    lol={'a': 'League', 'c': 'of', 'e': 'Legends',} lol Out[67]: {'a': 'League', 'c': 'of', 'e': 'Legends'} lol['a'] Out[68]: 'League' lol.get('e') Out[69]: 'Legends'

    >>keys() 获取所有键

    >>values() 获取所有值

    >>items() 获取所有键值对

    lol.keys() Out[70]: ['a', 'c', 'e'] lol.values() Out[71]: ['League', 'of', 'Legends'] lol.items() Out[72]: [('a', 'League'), ('c', 'of'), ('e', 'Legends')] >>copy() 复制

    转载请注明原文地址: https://ju.6miu.com/read-1125245.html

    最新回复(0)