zoukankan      html  css  js  c++  java
  • 【Python基础】lpthw

      1. 字典和列表的区别

      对于列表,它是一些项的有序排列,只能通过数值来进行索引;对于字典,则可以通过许多东西进行索引,它采用键-值映射的方式,不存在一个特定的顺序,因此不能用类似列表的数值索引,但它的键可以是数值。

    1 stuff = {'name':'zed','age':18,'weight':'50kg'}
    2 print(stuff['name'])
    3 print(stuff['age'])
    4 stuff['age'] = 40
    5 print(stuff["age"])
    6 stuff[1] = 'test'       # 在列表中创建一个新的键值对
    7 print(stuff[1])
    8 print(stuff)

      输出为

    zed
    18
    40
    test
    {'name': 'zed', 'age': 40, 'weight': '50kg', 1: 'test'}

      2. 删除字典中的内容

      del dict['key_name']

      3. 编程练习

     1 # create a mapping of state to abbreviation
     2 states = {
     3 'Oregon':'OR',
     4 'Florida':'FL',
     5 'California':'CA',
     6 'New York':'NY',
     7 'Michigan':'MI'
     8 }
     9 
    10 # create a basic set of  states and some cities in them
    11 cities = {
    12 'CA':'San Francisco',
    13 'MI':'Detroit',
    14 'FL':'Jacksonville'
    15 }
    16 
    17 # add some mor cities
    18 cities['NY'] = 'New York'
    19 cities['OR'] = 'Portland'
    20 
    21 # print out some cities
    22 print('-' * 10)
    23 print("NY state has: ",cities['NY'])
    24 print("OR state has: ",cities['OR'])
    25 
    26 # print some states
    27 print('-' * 10)
    28 print("Michigan's abbreviation is: ",states['Michigan'])
    29 print("Florida's abbreviation is: ",states['Florida'])
    30 
    31 # do it by using the sate then cities dict
    32 print('-' * 10)
    33 print("Michigan has: ", cities[states['Michigan']])
    34 print("Florida has: ", cities[states['Florida']])
    35 
    36 # print every state abbreviation
    37 print('-' * 10)
    38 for state, abbrev in list(states.items()):
    39     print(f"{state} is abbreviated as {abbrev}.")
    40 
    41 # print every city in state
    42 print('-' * 10)
    43 for abbrev, city in list(cities.items()):
    44     print(f"{abbrev} has the city {city}.")
    45 
    46 # now do both at the same time
    47 print('-' * 10)
    48 for state, abbrev in list(states.items()):
    49     print(f"{state} is abbreviated as {abbrev} and has city {cities[abbrev]}")
    50 
    51 print('-' * 10)
    52 # safely get a abbreviation by state that might not be there
    53 state = states.get('Texas')
    54 
    55 if not state:
    56     print(f'Sorry, no Texas.')
    57 
    58 # get a city with a default value
    59 city = cities.get('Tx','Does not exist')
    60 print(f"The city for the state 'TX' is: {city}")
    View Code

      输出

    ----------
    NY state has:  New York
    OR state has:  Portland
    ----------
    Michigan's abbreviation is:  MI
    Florida's abbreviation is:  FL
    ----------
    Michigan has:  Detroit
    Florida has:  Jacksonville
    ----------
    Oregon is abbreviated as OR.
    Florida is abbreviated as FL.
    California is abbreviated as CA.
    New York is abbreviated as NY.
    Michigan is abbreviated as MI.
    ----------
    CA has the city San Francisco.
    MI has the city Detroit.
    FL has the city Jacksonville.
    NY has the city New York.
    OR has the city Portland.
    ----------
    Oregon is abbreviated as OR and has city Portland
    Florida is abbreviated as FL and has city Jacksonville
    California is abbreviated as CA and has city San Francisco
    New York is abbreviated as NY and has city New York
    Michigan is abbreviated as MI and has city Detroit
    ----------
    Sorry, no Texas.
    The city for the state 'TX' is: Does not exist
    View Code

      4. 上述练习中的语法点

      ① 向字典中添加键值对

    dict['key'] = value

      ② 字典的嵌套

      例如dict1的值是dict2的键时,可以做如下嵌套

    dict2[dict1['key1']]

      ③ dict.items()函数

      以列表的形式返回可遍历的(键,值)元组数组。

      参数:无。

      书中所用加list()的形式和不加list()实现的功能似乎一致。

     1 states = {
     2 'Oregon':'OR',
     3 'Florida':'FL',
     4 'California':'CA',
     5 'New York':'NY',
     6 'Michigan':'MI'
     7 }
     8 
     9 for state, abbr in states.items():
    10     print(state,abbr)
    11 
    12 for state, abbr in list(states.items()):
    13     print(state,abbr)

      ④ dict.get()函数

      用于返回dict中指定键的值,如果键不在dict中,则返回设置的默认值,语法如下

    dict.get(key, default = None)
    dict.get('TX', 'Does not exist.')

      5. 字典键的特性

      字典的值可以是python中的任何数据类型,也可以是用户自定义的,但字典的键不行。

      ① 字典的键不可以重复定义,如果一个键在字典中被定义两次,则只会记住最后一个值,如

    1 dict = {'name':'Tom','age':18,'height':'170 cm','name':'Jerry'}
    2 print("dict['name']: {}".format(dict['name']))

      输出为

    dict['name']: Jerry

      ② 字典的值必须是不可变的,因此只能使用数值,字符串或者元组,而不能使用列表,如

    1 dict = {['name']:'Tom','age':18,'height':'170 cm'}
    2 print("dict[['name']]: {}".format(dict[['name']]))

      报错

    Traceback (most recent call last):
      File "ex23.py", line 1, in <module>
        dict = {['name']:'Tom','age':18,'height':'170 cm'}
    TypeError: unhashable type: 'list'

      6.字典的内置函数

      len(dict): 求字典长度

      str(dict): 以可打印的字符串的形式返回列表

      type(variable): 返回输入变量的类型,对字典就是<class 'dict'>

      7. 字典的常用操作

      dict.clear()  删除字典中所有元素

      dict.copy()  返回一个字典的浅复制 【参考】直接赋值和copy的区别

      dict.fromkeys(sequence[, value]) 创建一个新的字典,以序列sequence中的元素做字典的键,value为所有键对应的初始值

       key in dict 如果key在dict中,返回True,否则返回False

      dict.keys() 返回一个由所有键组成的迭代器,可以用list转换为列表(注意与dict.items()的区别,items()是直接返回列表)

      dictl.values() 返回一个由所有值组成的迭代器,可以用list转换为列表

      dict.setdefault(key, default = None) 和dict.get()类似,但如果key不在dict中则会添加这个键并将其值设为default

      dict1.update(dict2) 用dict2的键值对更新dict1

      dict.pop(key[,default]) 删除字典中给定key所给定的值,返回被删除的值;如果key不存在,则必须设定default的值(否则报错),并且函数将返回default的值

      8. dict.popitem() 详解

      官方文档:“Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. ”

           "Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair."

      在3.7版本以前,popitem是按所谓的“随机”顺序从字典中取出值的。在3.7以后的版本,官方文档对此作出了修改,明确指出popitem()是按照“后进先出”的顺序取出并返回字典中的键值对的。也就是说,其返回的是最后一个被添加到字典中的键值对。

    1 dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    2 print(dict)
    3 print(dict.popitem())
    4 print(dict)
    5 dict['e'] = 5
    6 print(dict.popitem())

      输出为

    {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    ('d', 4)
    {'a': 1, 'b': 2, 'c': 3}
    ('e', 5)

      9. get()  pop()  popitem() 的安全性讨论

      get() 可以为key设定缺省值,也可以不设定。当没有设置default时,如果dict中没有输入的key,则返回default的缺省值None;是一种相对安全的方法。 

      pop()也可以设定缺省值,如果不设定,而key又不存在于dict中,则也会报错。

      popitem()不能设定缺省值,如果dict为空时,dict.popitem()会报错:KeyError

      

  • 相关阅读:
    [leetcode]34.Find First and Last Position of Element in Sorted Array找区间
    [leetcode]278. First Bad Version首个坏版本
    [leetcode]367. Valid Perfect Square验证完全平方数
    [leetcode]45. Jump Game II青蛙跳(跳到终点最小步数)
    [leetcode]55. Jump Game青蛙跳(能否跳到终点)
    [leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)
    [leetcode]27. Remove Element删除元素
    [leetcode]20. Valid Parentheses有效括号序列
    [leetcode]15. 3Sum三数之和
    C#中的局部类型
  • 原文地址:https://www.cnblogs.com/cry-star/p/10650858.html
Copyright © 2011-2022 走看看