第1章、基础

1、几个小知识点

  • 多用 help() 帮助文档
  • 除法运算
  1. / 除法运算,得到结果为浮点数;
  2. // 整除运算,得到整数值(向下取整);
  3. % 取余操作 (结果符号与除数符号相同),本质上: x % y = x - (x // y) * y
  4. >>> 10 % 3
  5. 1
  6. >>> -10 % 3
  7. 2
  8. >>> 10 % -3
  9. -2
  10. >>> -10 % -3
  11. -1
  12. >>> 3 % 10
  13. 3
  14. >>> -3 % 10
  15. 7
  16. >>> 3 % -10
  17. -7
  18. >>> -3 % -10
  19. -3
  • 进制
  1. 十六进制 0x开头
  2. 八进制 0开头
  3. 二进制 0b开头
  4. >>> 0xAF
  5. 175
  6. >>> 010
  7. 8
  8. >>> 0b1011010010
  9. 722
  • 变量

Python变量没有默认值;

表达式是一些东西,而语句做一些事情

  • 获取键盘输入
  1. input()函数,返回字符串
  2. >>> x = input("x: ")
  3. x: 34
  4. >>> y = input("y: ")
  5. y: 42
  6. >>> print(int(x) * int(y))
  7. 1428
  • 内置函数和模块
  1. >>> 2 ** 3
  2. 8
  3. >>> pow(2,3)
  4. 8
  5. >>> abs(-10)
  6. 10
  7. >>> 2 // 3
  8. 0
  9. >>> round(2/3)
  10. 1
  11. >>> round(1.4)
  12. 1
  13. >>> round(1.5) # 偶数
  14. 2
  15. >>> round(1.6)
  16. 2
  17. >>> round(2.5) # 偶数
  18. 2
  19. >>> round(2.55, 1)
  20. 2.5
  21. >>> int(30.4)
  22. 30
  23. >>> import math # 导入模块
  24. >>> math.floor(30.4)
  25. 30
  26. >>> math.ceil(30.4)
  27. 31
  28. >>> from math import sqrt # 从模块中导入函数
  29. >>> sqrt(9)
  30. 3.0
  31. >>> sqrt(-1)
  32. Traceback (most recent call last):
  33. File "<stdin>", line 1, in <module>
  34. ValueError: math domain error
  35. # 复数模块
  36. >>> import cmath
  37. >>> cmath.sqrt(-1)
  38. 1j
  39. >>> cmath.sqrt(-8j)
  40. (2-2j)

2、字符串

  • 单引号、双引号、三引号、反斜杠
  • 字符串拼接 +
  • str 与 repr
  1. >>> print(repr("Hello,\nworld!")) # 面向程序表达式
  2. 'Hello,\nworld!'
  3. >>> print(str("Hello,\nworld!")) # 面向用户
  4. Hello,
  5. world!
  • 原始字符串:原始含反斜杠的字符串,如:路径。
  1. """
  2. 加反斜杠转义;
  3. 字符串前加r,作为原始字符串不被转义
  4. """
  5. >>> print("C:\now")
  6. C:
  7. ow
  8. >>> print("C:\\now")
  9. C:\now
  10. >>> print(r"C:\now")
  11. C:\now
  12. #注意:反斜杠结尾的字符串
  13. >>> print(r"C:\now\day\")
  14. File "<stdin>", line 1
  15. print(r"C:\now\day\")
  16. ^
  17. SyntaxError: EOL while scanning string literal
  18. >>> print(r"C:\now\day" + "\\")
  19. C:\now\day\
  • Unicode:码点和名称 (简单了解)

    • 使用16或32位的十六进制字面量(分别加上前缀\u或\U)

    • 使用字符的Unicode名称(\N{name})

  • 字节类型:不可变的bytes 和 可变的bytearray。 'b'开头

    • Python bytes字面量只支持ASCII标准中的128个字符,而余下的128个值必须用转义序列表示
    • 进行单字节编码时,依然使用ASCII编码,以便与较旧的系统兼容;但对于不在这个范围内的字符,使用多个字节(最多为6个)进行编码
    1. >>> b'Hello, world!'
    2. b'Hello, world!'
    3. >>> "Hello, world!".encode("ASCII")
    4. b'Hello, world!'
    5. >>> "Hello, world!".encode("UTF-8")
    6. b'Hello, world!'
    7. >>> "Hello, world!".encode("UTF-32")
    8. b'\xff\xfe\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00,\x00\x00\x00\x00\x00\x00w\x00\x00\x00o\x00\x00\x00r\x00\x00\x00l\x00\x00\x00d\x00\x00\x00!\x00\x00\x00'
    9. >>> len("How long is this?".encode("UTF-8"))
    10. 17
    11. >>> len("How long is this?".encode("UTF-32"))
    12. 72
    13. >>> bytes("Hællå, wørld!", encoding="utf-8")
    14. b'H\xc3\xa6ll\xc3\xa5, w\xc3\xb8rld!'
    15. >>> str(b'H\xc3\xa6ll\xc3\xa5, w\xc3\xb8rld!', encoding="utf-8")
    16. 'Hællå, wørld!'
    1. >>> x = bytearray(b"Hello!")
    2. >>> x[1] = ord(b"u")
    3. >>> x
    4. bytearray(b'Hullo!')
    5. >>> chr(65)
    6. 'A'
    7. >>> ord("A")
    8. 65

第2章 列表与元组

1、序列

  • 列表是可以修改的,而元组不可以

  • 索引、切片、相加、相乘和成员资格检查

  • 确定序列的长度以及找出序列中最大和最小的元素

  • 迭代

  1. >>> [1, 2, 3] + [4, 5, 6]
  2. [1, 2, 3, 4, 5, 6]
  3. # 初始化10个元素的列表
  4. >>> sequence = [None] * 10
  5. >>> sequence
  6. [None, None, None, None, None, None, None, None, None, None]
  7. in
  8. not in
  9. >>> "yt" in "Python"
  10. True
  11. >>> "x" in "Python"
  12. False
  13. >>> "a" in ["a", "b", 0]
  14. True
  15. >>> "0" in ["a", "b", 0]
  16. False
  17. len(list)、max(list)、min(list)

2、列表

  1. # 字符串 转 列表
  2. >>> list('Hello')
  3. ['H', 'e', 'l', 'l', 'o']
  4. >>> "H-e-l-l-o".split("-")
  5. ['H', 'e', 'l', 'l', 'o']
  6. # 列表 转 字符串
  7. >>> "".join(['H', 'e', 'l', 'l', 'o'])
  8. 'Hello'
  9. >>> "-".join(['H', 'e', 'l', 'l', 'o'])
  10. 'H-e-l-l-o'
  11. # 修改列表:给元素赋值
  12. >>> x = [1, 1, 1]
  13. >>> x[1] = 2
  14. >>> x
  15. [1, 2, 1]
  16. # 删除元素
  17. >>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
  18. >>> del names[2]
  19. >>> names
  20. ['Alice', 'Beth', 'Dee-Dee', 'Earl']
  21. # 给切片赋值
  22. >>> name = list('Perl')
  23. >>> name
  24. ['P', 'e', 'r', 'l']
  25. >>> name[2:] = list('ar')
  26. >>> name
  27. ['P', 'e', 'a', 'r']
  28. >>> name = list('Perl')
  29. >>> name[1:] = list('ython')
  30. >>> name
  31. ['P', 'y', 't', 'h', 'o', 'n']
  32. >>> numbers
  33. [1, 2, 3, 4, 5]
  34. >>> numbers[1:4] = []
  35. >>> numbers
  36. [1, 5]
  37. # append 就地添加
  38. >>> lst = [1, 2, 3]
  39. >>> lst.append(4)
  40. >>> lst
  41. [1, 2, 3, 4]
  42. # clear 就地清空
  43. >>> lst = [1, 2, 3]
  44. >>> lst.clear()
  45. >>> lst
  46. []
  47. # copy 复制成副本 等价于 a[:]或list(a)
  48. >>> a = [1, 2, 3]
  49. >>> b = a
  50. >>> b[1] = 4
  51. >>> a
  52. [1, 4, 3]
  53. >>> a = [1, 2, 3]
  54. >>> b = a.copy()
  55. >>> b[1] = 4
  56. >>> a
  57. [1, 2, 3]
  58. # count计数指定元素出现次数
  59. >>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to')
  60. 2
  61. >>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
  62. >>> x.count(1)
  63. 2
  64. >>> x.count([1, 2])
  65. 1
  66. # index在列表中查找指定值第一次出现的索引。
  67. >>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
  68. >>> knights.index('who')
  69. 4
  70. >>> knights.index('herring')
  71. Traceback (innermost last):
  72. File "<pyshell>", line 1, in ?
  73. knights.index('herring')
  74. ValueError: list.index(x): x not in list
  75. # extend 就地拼接,效率高
  76. >>> a = [1, 2, 3]
  77. >>> b = [4, 5, 6]
  78. >>> a.extend(b)
  79. >>> a
  80. [1, 2, 3, 4, 5, 6]
  81. >>> a = [1, 2, 3]
  82. >>> b = [4, 5, 6]
  83. >>> a + b
  84. [1, 2, 3, 4, 5, 6]
  85. >>> a
  86. [1, 2, 3]
  87. # insert
  88. >>> numbers = [1, 2, 3, 5, 6, 7]
  89. >>> numbers.insert(3, 'four')
  90. >>> numbers
  91. [1, 2, 3, 'four', 5, 6, 7]
  92. # pop从列表中删除一个元素(末尾为最后一个元素),并返回这一元素。
  93. >>> x = [1, 2, 3]
  94. >>> x.pop()
  95. 3
  96. >>> x
  97. [1, 2]
  98. >>> x.pop(0)
  99. 1
  100. >>> x
  101. [2]
  102. # remove用于删除第一个为指定值的元素,就地删除,不返回值
  103. >>> x = ['to', 'be', 'or', 'not', 'to', 'be']
  104. >>> x.remove('be')
  105. >>> x
  106. ['to', 'or', 'not', 'to', 'be']
  107. >>> x.remove('bee')
  108. Traceback (innermost last):
  109. File "<pyshell>", line 1, in ?
  110. x.remove('bee')
  111. ValueError: list.remove(x): x not in list
  112. # reverse按相反的顺序排列列表中的元素,就地修改
  113. >>> x = [1, 2, 3]
  114. >>> x.reverse()
  115. >>> x
  116. [3, 2, 1]
  117. >>> x = [1, 2, 3]
  118. >>> list(reversed(x))
  119. [3, 2, 1]
  120. # sort用于对列表就地排序,返回None
  121. >>> x = [4, 6, 2, 1, 7, 9]
  122. >>> x.sort()
  123. >>> x
  124. [1, 2, 4, 6, 7, 9]
  125. >>> x = [4, 6, 2, 1, 7, 9]
  126. >>> y = sorted(x)
  127. >>> x
  128. [4, 6, 2, 1, 7, 9]
  129. >>> y
  130. [1, 2, 4, 6, 7, 9]
  131. >>> sorted('Python')
  132. ['P', 'h', 'n', 'o', 't', 'y']
  133. list.sort(cmp=None, key=None, reverse=False)
  134. sorted(iterable, cmp=None, key=None, reverse=False)
  • 可以用append和pop实现 栈结构

3、元组

  1. >>> 42
  2. 42
  3. >>> 42,
  4. (42,)
  5. >>> 3 * (40 + 2)
  6. 126
  7. >>> 3 * (40 + 2,)
  8. (42, 42, 42)

第3章 字符串

  • 索引、切片、乘法、成员资格检查、长度、最小值和最大值

1、格式化

  1. # 1、%
  2. >>> "Hello, %s. %s enough for ya?" % ('world', 'Hot')
  3. 'Hello, world. Hot enough for ya?'
  4. # 2、Template $
  5. >>> from string import Template
  6. >>> Template("Hello, $who! $what enough for ya?").substitute(who="Mars", what="Dusty")
  7. 'Hello, Mars! Dusty enough for ya?'
  8. # format 推荐
  9. ## 位置
  10. >>> "{}, {} and {}".format("first", "second", "third")
  11. 'first, second and third'
  12. >>> "{0}, {1} and {2}".format("first", "second", "third")
  13. 'first, second and third'
  14. ## 索引可乱序
  15. >>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
  16. 'to be or not to be'
  17. ## 关键字参数:变量名
  18. >>> from math import pi
  19. >>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
  20. 'π is approximately 3.14.'
  21. ## f字符串
  22. >>> from math import e
  23. >>> f"Euler's constant is roughly {e}."
  24. "Euler's constant is roughly 2.718281828459045."
  1. # format 每个值都被插入字符串中,以替换用花括号括起的替换字段
  2. """
  3. 字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。除指定值外,还可指定值的特定部分,如列表的元素。
  4. """
  5. >>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
  6. '3 1 4 2'
  7. >>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
  8. '3 2 4 1'
  9. >>> "Mr {name[1]}".format(name=["Alfred", "Smoketoomuch"])
  10. 'Mr Smoketoomuch'
  11. >>> import math
  12. >>> "The {mod.__name__} module defines the value {mod.pi} for π".format(mod=math)
  13. 'The math module defines the value 3.141592653589793 for π'
  14. """
  15. 转换标志:跟在叹号后面的单个字符。当前支持的字符包括r(表示repr)、s(表示str)和a(表示ascii)。如果你指定了转换标志,将不使用对象本身的格式设置机制,而是使用指定的函数将对象转换为字符串,再做进一步的格式设置。
  16. """
  17. >>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
  18. π 'π' '\u03c0'
  19. >>> "The number is {num}, {num:f}, {num:b}".format(num=42)
  20. 'The number is 42, 42.000000, 101010'
  21. ## 宽度
  22. >>> "{num:10}".format(num=3)
  23. ' 3'
  24. >>> "{name:10}".format(name="Bob")
  25. 'Bob '
  26. ## 精度
  27. >>> "Pi day is {pi:.2f}".format(pi=pi)
  28. 'Pi day is 3.14'
  29. >>> "{pi:10.2f}".format(pi=pi)
  30. ' 3.14'
  31. >>> "{:.5}".format("Guido van Rossum")
  32. 'Guido'
  33. ## 千位分隔符
  34. >>> 'One googol is {:,}'.format(10**100)
  35. 'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
  36. """
  37. 格式说明符:跟在冒号后面的表达式(这种表达式是使用微型格式指定语言表示的)。格式说明符让我们能够详细地指定最终的格式,包括格式类型(如字符串、浮点数或十六进制数),字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对齐和填充方式。
  38. """
  39. >>> '{:010.2f}'.format(pi)
  40. '0000003.14'
  41. ## 左对齐、右对齐和居中
  42. >>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
  43. 3.14
  44. 3.14
  45. 3.14
  46. >>> "{:$^15}".format(" WIN BIG ")
  47. '$$$ WIN BIG $$$'
  48. >>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
  49. 3.14
  50. -3.14
  51. >>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
  52. 3.14
  53. -3.14
  54. >>> print('{0:10.2f}\n{1:=10.2f}'.format(pi, -pi))
  55. 3.14
  56. - 3.14
  57. >>> print('{0:-.2}\n{1:-.2}'.format(pi, -pi)) #默认设置
  58. 3.1
  59. -3.1
  60. >>> print('{0:+.2}\n{1:+.2}'.format(pi, -pi))
  61. +3.1
  62. -3.1
  63. >>> print('{0: .2}\n{1: .2}'.format(pi, -pi))
  64. 3.1
  65. -3.1
  66. >>> "{:b}".format(42)
  67. '101010'
  68. >>> "{:#b}".format(42)
  69. '0b101010'
  70. >>> "{:g}".format(42)
  71. '42'
  72. >>> "{:#g}".format(42)
  73. '42.0000'

2、字符串方法

  1. # center通过在两边添加填充字符(默认为空格)让字符串居中。 ljust、rjust和zfill
  2. >>> "The Middle by Jimmy Eat World".center(39)
  3. ' The Middle by Jimmy Eat World '
  4. >>> "The Middle by Jimmy Eat World".center(39, "*")
  5. '*****The Middle by Jimmy Eat World*****'
  6. # find 在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。 rfind、index、rindex、count、startswith、endswith
  7. >>> 'With a moo-moo here, and a moo-moo there'.find('moo')
  8. 7
  9. >>> title = "Monty Python's Flying Circus"
  10. >>> title.find('Python')
  11. 6
  12. >>> title.find('Zirquss')
  13. -1
  14. >>> subject = '$$$ Get rich now!!! $$$'
  15. >>> subject.find('$$$')
  16. 0
  17. >>> subject.find('$$$', 1) # 只指定了起点
  18. 20
  19. >>> subject.find('!!!')
  20. 16
  21. >>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
  22. -1
  23. # join 合并序列的元素
  24. >>> seq = [1, 2, 3, 4, 5]
  25. >>> sep = '+'
  26. >>> sep.join(seq) # 尝试合并一个数字列表
  27. Traceback (most recent call last):
  28. File "<stdin>", line 1, in ?
  29. TypeError: sequence item 0: expected string, int found
  30. >>> seq = ['1', '2', '3', '4', '5']
  31. >>> sep.join(seq) # 合并一个字符串列表
  32. '1+2+3+4+5'
  33. >>> print('C:' + '\\'.join(dirs))
  34. C:\usr\bin\env
  35. # lower、capitalize、casefold、swapcase、title、upper
  36. # replace 指定子串都替换为另一个字符串,并返回替换后的结果
  37. >>> 'This is a test'.replace('is', 'eez')
  38. 'Theez eez a test'
  39. # split 用于将字符串拆分为序列
  40. >>> '1+2+3+4+5'.split('+')
  41. ['1', '2', '3', '4', '5']
  42. >>> '/usr/bin/env'.split('/')
  43. ['', 'usr', 'bin', 'env']
  44. >>> 'Using the default'.split()
  45. ['Using', 'the', 'default']
  46. # strip 将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果; lstrip、rstrip
  47. >>> ' internal whitespace is kept '.strip()
  48. 'internal whitespace is kept'
  49. >>> names = ['gumby', 'smith', 'jones']
  50. >>> name = 'gumby '
  51. >>> if name in names: print('Found it!')
  52. ...
  53. >>> if name.strip() in names: print('Found it!')
  54. ...
  55. Found it!
  56. >>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
  57. 'SPAM * for * everyone'
  58. # translate 进行单字符替换;同时替换多个字符
  59. >>> table = str.maketrans('cs', 'kz')
  60. >>> table
  61. {115: 122, 99: 107}
  62. >>> 'this is an incredible test'.translate(table)
  63. 'thiz iz an inkredible tezt'
  64. >>> table = str.maketrans('cs', 'kz', ' ')
  65. >>> 'this is an incredible test'.translate(table)
  66. 'thizizaninkredibletezt'
  67. # 判断字符串是否满足特定的条件
  68. """
  69. isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、
  70. isprintable、isspace、istitle、isupper
  71. """

第4章 字典

  • 字典由键及其相应的值组成,这种键-值对称为项(item)
  1. ## 字典
  2. >>> items = [('name', 'Gumby'), ('age', 42)]
  3. >>> d = dict(items)
  4. >>> d
  5. {'age': 42, 'name': 'Gumby'}
  6. >>> d = dict(name='Gumby', age=42)
  7. >>> d
  8. {'age': 42, 'name': 'Gumby'}
  9. """
  10. len(d) 返回字典d包含的项(键-值对)数。
  11. d[k] 返回与键k相关联的值。
  12. d[k] = v 将值v关联到键k。
  13. del d[k] 删除键为k的项。
  14. k in d 检查字典d是否包含键为k的项。
  15. """
  16. """
  17. 键的类型:字典中的键可以是任何不可变的类型,如整数、浮点数(实数)、字符串或元组。
  18. 自动添加:即便是字典中原本没有的键,也可以给它赋值,这将在字典中创建一个新项。
  19. 成员资格:表达式k in d(其中d是一个字典)查找的是键而不是值。
  20. """
  21. # 通过字典 格式化字符串
  22. >>> phonebook
  23. {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
  24. >>> "Cecil's phone number is {Cecil}.".format_map(phonebook)
  25. "Cecil's phone number is 3258."
  26. # clear删除所有的字典项,就地执行,返回None。
  27. >>> x = {}
  28. >>> y = x
  29. >>> x['key'] = 'value'
  30. >>> y
  31. {'key': 'value'}
  32. >>> x = {}
  33. >>> y
  34. {'key': 'value'}
  35. 下面是第二个场景:
  36. >>> x = {}
  37. >>> y = x
  38. >>> x['key'] = 'value'
  39. >>> y
  40. {'key': 'value'}
  41. >>> x.clear()
  42. >>> y
  43. {}
  44. ## copy返回一个新字典,其包含的键值对与原来的字典相同,浅复制
  45. >>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
  46. >>> y = x.copy()
  47. >>> y['username'] = 'mlh'
  48. >>> y['machines'].remove('bar')
  49. >>> y
  50. {'username': 'mlh', 'machines': ['foo', 'baz']}
  51. >>> x
  52. {'username': 'admin', 'machines': ['foo', 'baz']}
  53. ## deepcopy 深复制
  54. >>> from copy import deepcopy
  55. >>> d = {}
  56. >>> d['names'] = ['Alfred', 'Bertrand']
  57. >>> c = d.copy()
  58. >>> dc = deepcopy(d)
  59. >>> d['names'].append('Clive')
  60. >>> c
  61. {'names': ['Alfred', 'Bertrand', 'Clive']}
  62. >>> dc
  63. {'names': ['Alfred', 'Bertrand']}
  64. # fromkeys创建一个新字典,其中包含指定的键,且每个键对应的值都是None
  65. >>> {}.fromkeys(['name', 'age'])
  66. {'age': None, 'name': None}
  67. >>> dict.fromkeys(['name', 'age'])
  68. {'age': None, 'name': None}
  69. >>> dict.fromkeys(['name', 'age'], '(unknown)')
  70. {'age': '(unknown)', 'name': '(unknown)'}
  71. ## get
  72. >>> d = {}
  73. >>> print(d['name'])
  74. Traceback (most recent call last):
  75. File "<stdin>", line 1, in ?
  76. KeyError: 'name'
  77. >>> print(d.get('name'))
  78. None
  79. >>> d.get('name', 'N/A')
  80. 'N/A'
  81. ## items返回一个包含所有字典项的列表,其中每个元素都为(key, value)的形式(字典视图)。字典项在列表中的排列顺序不确定。
  82. >>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
  83. >>> d.items()
  84. dict_items([('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')])
  85. # 字典视图不复制,它们始终是底层字典的反映
  86. >>> it = d.items()
  87. >>> len(it)
  88. 3
  89. >>> ('spam', 0) in it
  90. True
  91. >>> d['spam'] = 1
  92. >>> ('spam', 0) in it
  93. False
  94. >>> d['spam'] = 0
  95. >>> ('spam', 0) in it
  96. True
  97. ## keys返回一个字典视图,其中包含指定字典中的
  98. ## pop可用于获取与指定键相关联的值,并将该键值对从字典中删除。
  99. >>> d = {'x': 1, 'y': 2}
  100. >>> d.pop('x')
  101. 1
  102. >>> d
  103. {'y': 2}
  104. ## popitem 随机地弹出一个字典项
  105. >>> d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
  106. >>> d.popitem()
  107. ('url', 'http://www.python.org')
  108. >>> d
  109. {'spam': 0, 'title': 'Python Web Site'}
  110. ## setdefault 获取与指定键相关联的值
  111. >>> d = {}
  112. >>> d.setdefault('name', 'N/A')
  113. 'N/A'
  114. >>> d
  115. {'name': 'N/A'}
  116. >>> d['name'] = 'Gumby'
  117. >>> d.setdefault('name', 'N/A')
  118. 'Gumby'
  119. >>> d
  120. {'name': 'Gumby'}
  121. ## update使用一个字典中的项来更新另一个字典。(字典拼接)
  122. ## values返回一个由字典中的值组成的字典视图,可以重复
  123. >>> d = {}
  124. >>> d[1] = 1
  125. >>> d[2] = 2
  126. >>> d[3] = 3
  127. >>> d[4] = 1
  128. >>> d.values()
  129. dict_values([1, 2, 3, 1])

第5章 print和import

1、print

  1. print(*objects, sep=' ', end='\n', file=sys.stdout)

2、import

  1. import somemodule
  2. from somemodule import somefunction
  3. from somemodule import somefunction, anotherfunction, yetanotherfunction
  4. from somemodule import *
  5. froom module1.module2 import somefunction
  6. import somemodule as othername

3、序列解包

  1. # 可同时(并行)给多个变量赋值
  2. >>> x, y, z = 1, 2, 3
  3. >>> print(x, y, z)
  4. 1 2 3
  5. # 交换变量值
  6. >>> x, y = y, x
  7. >>> print(x, y, z)
  8. 2 1 3
  9. # 解包
  10. >>> values = 1, 2, 3
  11. >>> values
  12. (1, 2, 3)
  13. >>> x, y, z = values
  14. >>> x
  15. 1
  16. # 字典解包
  17. >>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
  18. >>> key, value = scoundrel.popitem()
  19. >>> key
  20. 'girlfriend'
  21. >>> value
  22. 'Marion'
  23. # 序列包含的元素个数必须与你在等号左边列出的目标个数相同
  24. >>> a, b, *rest = [1, 2, 3, 4]
  25. >>> rest
  26. [3, 4]
  27. >>> name = "Albus Percival Wulfric Brian Dumbledore"
  28. >>> first, *middle, last = name.split()
  29. >>> middle
  30. ['Percival', 'Wulfric', 'Brian']
  31. >>> a, *b, c = "abc"
  32. >>> a, b, c
  33. ('a', ['b'], 'c')
  34. # 链式赋值
  35. x = y = somefunction() 等价于
  36. y = somefunction()
  37. x = y
  38. # 增强赋值
  39. x += 1

4、缩进

5、条件

  1. False None 0 "" () [] {}
  2. bool([]) == bool("") == False
  3. # 链式比较
  4. 0 < age < 100
  5. # is is not in not in
  6. # is:相同运算符
  7. # ==用来检查两个对象是否相等,而is用来检查两个对象是否相同(是同一个对象)。
  8. >>> x = y = [1, 2, 3]
  9. >>> z = [1, 2, 3]
  10. >>> x == y
  11. True
  12. >>> x == z
  13. True
  14. >>> x is y
  15. True
  16. >>> x is z
  17. False
  18. # in:成员资格运算符
  19. # 字符串和序列的比较
  20. # 字母排列顺序,但字母都是Unicode字符,它们是按码点排列的
  21. >>> "alpha" < "beta"
  22. True
  23. >>> "a" < "B"
  24. False
  25. >>> [1, 2] < [2, 1]
  26. True
  27. >>> [2, [1, 4]] < [2, [1, 5]]
  28. True
  29. # 短路逻辑 and or not

6、断言

  1. # assert 检查点
  2. >>> age = 10
  3. >>> assert 0 < age < 100
  4. >>> age = -1
  5. >>> assert 0 < age < 100
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in ?
  8. AssertionError
  9. # 加断言检查异常说明
  10. >>> age = -1
  11. >>> assert 0 < age < 100, 'The age must be realistic'
  12. Traceback (most recent call last):
  13. File "<stdin>", line 1, in ?
  14. AssertionError: The age must be realistic

6、循环

  1. """
  2. while、for
  3. """
  4. for number in range(1,101):
  5. print(number)
  6. # 无序
  7. d = {'x': 1, 'y': 2, 'z': 3}
  8. for key in d:
  9. print(key, 'corresponds to', d[key])
  10. for key, value in d.items():
  11. print(key, 'corresponds to', value)

7、迭代工具

  1. names = ['anne', 'beth', 'george', 'damon']
  2. ages = [12, 45, 32, 102]
  3. # 并行迭代
  4. >>> list(zip(names, ages))
  5. [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
  6. for name, age in zip(names, ages):
  7. print(name, 'is', age, 'years old')
  8. # 当序列的长度不同时,函数zip将
  9. # 在最短的序列用完后停止“缝合”。
  10. >>> list(zip(range(5), range(100000000)))
  11. [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
  12. # 迭代时取索引
  13. for index, string in enumerate(strings):
  14. if 'xxx' in string:
  15. strings[index] = '[censored]'
  16. # 反向迭代和排序后再迭代
  17. >>> sorted([4, 3, 6, 8, 3])
  18. [3, 3, 4, 6, 8]
  19. >>> sorted('Hello, world!')
  20. [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
  21. >>> list(reversed('Hello, world!'))
  22. ['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
  23. >>> ''.join(reversed('Hello, world!'))
  24. '!dlrow ,olleH'

8、跳出循环

  1. break
  2. continue
  3. while True/break

Python基础教程(第3版)学习笔记的更多相关文章

  1. HTML5与CSS3基础教程第八版学习笔记11~15章

    第十一章,用CSS进行布局 开始布局注意事项 1.内容与显示分离 2.布局方法:固定宽度和响应式布局 固定宽度,整个页面和每一栏都有基于像素的宽度 响应式布局也称为流式页面,使用百分数定义宽度 3.浏 ...

  2. HTML5与CSS3基础教程第八版学习笔记16-21章

    第十六章,表单 HTML5引入了新的表单元素.输入类型和属性,以及内置的对必填字段.电子邮件地址.URL以及定制模式验证. 元素: <input type="email"&g ...

  3. HTML5与CSS3基础教程第八版学习笔记7~10章

    第七章,CSS构造块 CSS里有控制基本格式的属性(font-size,color),有控制布局的属性(position,float),还有决定访问者打印时在哪里换页的打印控制元素.CSS还有很多控制 ...

  4. HTML5与CSS3基础教程第八版学习笔记1~6章

    第一章,网页的构造块 网页主要包括三个部分: 1.文本内容(纯文字) 2.对其他文件的引用:图像,音频,视频,样式表文件,js文件 3.标记:对文本内容进行描述并确保引用正确地工作 注:所有这些成分都 ...

  5. Python 基础教程(第二版)笔记 (2) 字典

    P59 字典方法 1. clear 2. copy, deepcopy 3. fromkeys 4. get 比下标安全 5. has_key 6. items, iteritems 7. keys, ...

  6. Python 基础教程(第二版)笔记 (1)

    P22 除非对 input 有特别的需要,否则应该尽可能使用 raw_input 函数. 长字符串,跨多行,用三个引号代替普通引号.并且不需要使用反斜线进行转义. P23 原始字符串 print r' ...

  7. 《python基础教程(第二版)》学习笔记 文件和素材(第11章)

    <python基础教程(第二版)>学习笔记 文件和素材(第11章) 打开文件:open(filename[,mode[,buffering]]) mode是读写文件的模式f=open(r' ...

  8. 《python基础教程(第二版)》学习笔记 类和对象(第7章)

    <python基础教程(第二版)>学习笔记 类和对象(第7章) 定义类class Person:    def setName(self,name):        self.name=n ...

  9. 《python基础教程(第二版)》学习笔记 函数(第6章)

    <python基础教程(第二版)>学习笔记 函数(第6章) 创建函数:def function_name(params):  block  return values 记录函数:def f ...

  10. 《python基础教程(第二版)》学习笔记 语句/循环/条件(第5章)

    <python基础教程(第二版)>学习笔记 语句/循环/条件(第5章) print 'AB', 123 ==> AB 123 # 插入了一个空格print 'AB', 'CD' == ...

随机推荐

  1. C# 控件 RichTextBox 显示行号,并且与Panel相互联动

    我们在使用到WINFORM窗体工作中,要求RichTextBox 加入行号: 之前有看到大牛们写的,但是太复杂繁多,而且有用双TextBox进行联动,非常不错,今天我们尝试RichTextBox +P ...

  2. wait,notify,notifyAll详细介绍

    https://www.cnblogs.com/pangyang/articles/5916349.html

  3. solr学习篇(四) java使用solr简单查询(初识solrj)

    使用java实现solr查询 目录:1:导入jar包 2:核心类介绍 3:代码实现 4:注意事项 一 导入jar包 solrj可以使Java应用程序很方便的访问与操作solr. solrj有几个核心类 ...

  4. git 的一些指令

    作为一个前端,git的各种指令应该是需要掌握的,因为前一段时间遇到了一些问题,总觉得每次遇到点问题都去百度这样总归不大好,还是记录一下比较常见的一些指令吧.以后遇到新的再继续添加. 1. 新建本地分支 ...

  5. 使用animate.css

    今天有个一前辈来看了一下我的小程序啊,说写的还行就是可以不用只按照ui给的图写界面,自己可以添加一些动态的炫酷效果,不用不知道一用吓一跳啊,用之前觉得好好一个界面为什么要搞那些花里胡哨的东西,单纯一点 ...

  6. .net core跨平台应用研究-ubuntu core下配置.net core运行时

    引言 年初研究了一阵子.net core跨平台应用,先后发表了几篇应用研究的文章.因工作原因,忙于项目上线,有一阵子没来博客园写文章了.最近项目基本收尾,抽空翻了下自己的博客,廖廖几篇文章,真让人汗颜 ...

  7. 探究JavaScript闭包

    什么是JavaScript闭包? 刚开始知道这个词,就误以为是自动执行的匿名函数块. 比如说+function(){}(); 然而并不是,那么请看下面的例子: function init() { va ...

  8. LNMP与LAMP的工作原理

    LAMP的实现原理 LAMP=Linux+Apache+Mysql+PHP.​#工作原理:浏览器向服务器发送http请求,服务器 (Apache) 接受请求,由于php作为Apache的组件模块也会一 ...

  9. 代码作家Alpha冲刺阶段博客目录

    一.Scrum Meeting 1. [第六周会议记录] 2. [第七周会议记录] 二.测试报告 Alpha阶段测试报告 三.习得的软工原理/方法/技能  1. 在项目前期准备中,我们学会了一些页面设 ...

  10. PHP 输出XML字符串

    <?php echo htmlentities( $xml_string);?>