【《流畅的python》3.2-3.3节学习笔记】

前言

本文为《流畅的python》的3.2-3.3节的学习笔记。

字典推导


DIAL_CODES = [
    (86, 'China'),
    (91, 'India'),
    (1, 'United States'),
    (62, 'Indonesia'),
    (55, 'Brazil'),
    (92, 'Pakistan'),
    (880, 'Bangladesh'),
    (234, 'Nigeria'),
    (7, 'Russia'),
    (81, 'Japan'),
]

country_code = {country: code
                for code, country in DIAL_CODES}
print(country_code)
>>>
{'China': 86, 'India': 91, 'United States': 1, 'Indonesia': 62, 'Brazil': 55, 'Pakistan': 92, 'Bangladesh': 880, 'Nigeria': 234, 'Russia': 7, 'Japan': 81}

说明:字典推导和列表推导,生成器推导写法类似,使用{}包含key和value
本例中,DIAL_CODES为列表,用for循环得到每个元素,其类型为元组,用元组拆包的方法得到区域码和国家名。
在字典推导时,以国家名为key,区域码为value。


country_code1 = {code: country.upper()
                 for country, code in country_code.items()
                    if code < 66}
print(country_code1)
>>>
{1: 'UNITED STATES', 62: 'INDONESIA', 55: 'BRAZIL', 7: 'RUSSIA'}

说明:以上例生成的字典为base进行拆包,并过滤区域码小于66的地区,推导新字典。

dict.setdefault


import sys
import re

WORD_RE = re.compile(r'\w+')

def get():
    index = {}
    with open('D:\\new 1.txt', encoding='utf-8') as fp:
        for line_no, line in enumerate(fp, 1):
            #match: the match object
            for match in WORD_RE.finditer(line):
                word = match.group()
                column_no = match.start() + 1
                location = (line_no, column_no)
                #occurrences: a list to include the location(type: turple)
                #if key=word is not in dict, occurrences is set to null
                occurrences = index.get(word, [])#1st search key
                #add the new value
                occurrences.append(location)
                index[word] = occurrences#2nd search key
                #print(occurrences)
    for word in sorted(index, key=str.upper):
        print(word, index[word])
        pass

if __name__ == '__main__':
    get()
    #setdefault()
>>>
0 [(4, 26), (4, 31)]
1 [(21, 16)]
2 [(20, 13), (21, 13)]
4 [(20, 16), (24, 9)]
5 [(24, 12)]
abs [(12, 21)]
bool [(12, 16)]
class [(3, 1)]
def [(4, 5), (7, 5), (9, 5), (11, 5), (13, 5), (17, 5)]
from [(1, 1)]
hypot [(1, 18), (10, 16)]
import [(1, 11)]
math [(1, 6)]
other [(13, 23), (14, 22), (15, 22)]
print [(23, 1)]
r [(8, 25), (8, 29)]
return [(8, 9), (10, 9), (12, 9), (16, 9), (18, 9)]
scalar [(17, 23), (18, 32), (18, 49)]
self [(4, 18), (5, 9), (6, 9), (7, 18), (8, 36), (8, 44), (9, 17), (10, 22), (10, 30), (11, 18), (12, 25), (13, 17), (14, 13), (15, 13), (17, 17), (18, 23), (18, 40)]
v1 [(20, 1), (23, 7)]
v2 [(21, 1), (23, 12)]
Vector [(3, 7), (8, 17), (16, 16), (18, 16), (20, 6), (21, 6), (24, 2)]
x [(4, 24), (5, 14), (5, 18), (8, 41), (10, 27), (14, 9), (14, 18), (14, 28), (16, 23), (18, 28)]
y [(4, 29), (6, 14), (6, 18), (8, 49), (10, 35), (15, 9), (15, 18), (15, 28), (16, 26), (18, 45)]
__abs__ [(9, 9)]
__add__ [(13, 9)]
__bool__ [(11, 9)]
__init__ [(4, 9)]
__mul__ [(17, 9)]
__repr__ [(7, 9)]

说明:本例是查询所有字母数字字符串在文件里出现的位置。
字典key对应的value以occurrences表示,类型为列表,列表里每个位置以location表示,类型为元组。
occurrences = index.get(word, [])
使用get方法查询字典index里是否有key为word,如果没有则以[]作为默认值,这是第一次以key查询字典。
occurrences.append(location)
index[word] = occurrences
在occurrences得到新值后,重新对字典key和value赋值,这是第二次以key查询字典
以上三行可以通过dict.setdefault一行完成。


def setdefault():
    index = {}
    with open('D:\\new 1.txt', encoding='utf-8') as fp:
        for line_no, line in enumerate(fp, 1):
            #match: the match object
            for match in WORD_RE.finditer(line):
                word = match.group()
                column_no = match.start() + 1
                location = (line_no, column_no)
                index.setdefault(word,[]).append(location)
    for word in sorted(index, key=str.upper):
        print(word, index[word])
        pass

总结

本小节主要讲字典的相关内容,字典推导和setdefault方法的运用。

相关推荐

  1. 【《流畅python》3.2-3.3学习笔记

    2024-07-15 12:34:01       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 12:34:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 12:34:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 12:34:01       58 阅读
  4. Python语言-面向对象

    2024-07-15 12:34:01       69 阅读

热门阅读

  1. 科普文:Redis一问一答

    2024-07-15 12:34:01       17 阅读
  2. 加密方式种类有哪些

    2024-07-15 12:34:01       23 阅读
  3. redis高级

    2024-07-15 12:34:01       19 阅读
  4. Kotlin中let、apply、also、with、run的使用与区别

    2024-07-15 12:34:01       23 阅读
  5. MyBatis的原理?

    2024-07-15 12:34:01       22 阅读
  6. node.js的安装及学习(node/nvm/npm的区别)

    2024-07-15 12:34:01       24 阅读
  7. 数据结构与算法 —— Transformers之Pipeline

    2024-07-15 12:34:01       22 阅读
  8. 每日新闻掌握【2024年7月15日 星期一】

    2024-07-15 12:34:01       26 阅读
  9. Ubuntu软件安装与卸载

    2024-07-15 12:34:01       21 阅读
  10. params和data的差别,doc下载

    2024-07-15 12:34:01       21 阅读
  11. 【Go系列】 Go的高并发模式

    2024-07-15 12:34:01       18 阅读