第1章、基础

1、几个小知识点

  • 多用 help() 帮助文档
  • 除法运算
/  除法运算,得到结果为浮点数;
// 整除运算,得到整数值(向下取整);
%  取余操作 (结果符号与除数符号相同),本质上: x % y = x - (x // y) * y

>>> 10 % 3
1
>>> -10 % 3
2
>>> 10 % -3
-2
>>> -10 % -3
-1
>>> 3 % 10
3
>>> -3 % 10
7
>>> 3 % -10
-7
>>> -3 % -10
-3
  • 进制
十六进制  0x开头
八进制    0开头
二进制    0b开头


>>> 0xAF
175
>>> 010
8
>>> 0b1011010010
722
  • 变量

Python变量没有默认值;

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

  • 获取键盘输入
input()函数,返回字符串

>>> x = input("x: ")
x: 34
>>> y = input("y: ")
y: 42
>>> print(int(x) * int(y))
1428
  • 内置函数和模块
>>> 2 ** 3
8
>>> pow(2,3)
8

>>> abs(-10)
10

>>> 2 // 3
0
>>> round(2/3)
1
>>> round(1.4)
1
>>> round(1.5)  # 偶数
2
>>> round(1.6)
2
>>> round(2.5)  # 偶数
2
>>> round(2.55, 1)
2.5

>>> int(30.4)
30
>>> import math  # 导入模块
>>> math.floor(30.4)
30
>>> math.ceil(30.4)
31

>>> from math import sqrt  # 从模块中导入函数
>>> sqrt(9)
3.0

>>> sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error


# 复数模块
>>> import cmath
>>> cmath.sqrt(-1)
1j

>>> cmath.sqrt(-8j)
(2-2j)

2、字符串

  • 单引号、双引号、三引号、反斜杠
  • 字符串拼接 +
  • str 与 repr
>>> print(repr("Hello,\nworld!"))  # 面向程序表达式
'Hello,\nworld!'
>>> print(str("Hello,\nworld!"))   # 面向用户
Hello,
world!
  • 原始字符串:原始含反斜杠的字符串,如:路径。
"""
加反斜杠转义;
字符串前加r,作为原始字符串不被转义
"""

>>> print("C:\now")
C:
ow

>>> print("C:\\now")
C:\now

>>> print(r"C:\now")
C:\now


#注意:反斜杠结尾的字符串
>>> print(r"C:\now\day\")
File "<stdin>", line 1
print(r"C:\now\day\")
^
SyntaxError: EOL while scanning string literal

>>> print(r"C:\now\day" + "\\")
C:\now\day\
  • Unicode:码点和名称 (简单了解)

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

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

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

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

第2章 列表与元组

1、序列

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

  • 索引、切片、相加、相乘和成员资格检查
  • 确定序列的长度以及找出序列中最大和最小的元素

  • 迭代

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

# 初始化10个元素的列表
>>> sequence = [None] * 10
>>> sequence
[None, None, None, None, None, None, None, None, None, None]

in
not in

>>> "yt" in "Python"
True
>>> "x" in "Python"
False

>>> "a" in ["a", "b", 0]
True
>>> "0" in ["a", "b", 0]
False

len(list)、max(list)、min(list)

2、列表

# 字符串 转 列表
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']

>>> "H-e-l-l-o".split("-")
['H', 'e', 'l', 'l', 'o']

# 列表 转 字符串
>>> "".join(['H', 'e', 'l', 'l', 'o'])
'Hello'
>>> "-".join(['H', 'e', 'l', 'l', 'o'])
'H-e-l-l-o'



# 修改列表:给元素赋值
>>> x = [1, 1, 1]
>>> x[1] = 2
>>> x
[1, 2, 1]

# 删除元素
>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']

# 给切片赋值
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar')
>>> name
['P', 'e', 'a', 'r']

>>> name = list('Perl')
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']

>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[1:4] = []
>>> numbers
[1, 5]

# append 就地添加
>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

# clear 就地清空
>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]

# copy 复制成副本  等价于 a[:]或list(a)
>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 4
>>> a
[1, 4, 3]

>>> a = [1, 2, 3]
>>> b = a.copy()
>>> b[1] = 4
>>> a
[1, 2, 3]

# count计数指定元素出现次数
>>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to')
2
>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1



# index在列表中查找指定值第一次出现的索引。
>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
>>> knights.index('herring')
Traceback (innermost last):
File "<pyshell>", line 1, in ?
knights.index('herring')
ValueError: list.index(x): x not in list

# extend 就地拼接,效率高
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]


# insert

>>> numbers = [1, 2, 3, 5, 6, 7]
>>> numbers.insert(3, 'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]

# pop从列表中删除一个元素(末尾为最后一个元素),并返回这一元素。
>>> x = [1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

# remove用于删除第一个为指定值的元素,就地删除,不返回值
>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x.remove('bee')
Traceback (innermost last):
File "<pyshell>", line 1, in ?
x.remove('bee')
ValueError: list.remove(x): x not in list

# reverse按相反的顺序排列列表中的元素,就地修改
>>> x = [1, 2, 3]
>>> x.reverse()
>>> x
[3, 2, 1]

>>> x = [1, 2, 3]
>>> list(reversed(x))
[3, 2, 1]

# sort用于对列表就地排序,返回None
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]


>>> x = [4, 6, 2, 1, 7, 9]
>>> y = sorted(x)
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]

>>> sorted('Python')
['P', 'h', 'n', 'o', 't', 'y']


list.sort(cmp=None, key=None, reverse=False)
sorted(iterable, cmp=None, key=None, reverse=False)
  • 可以用append和pop实现 栈结构

3、元组

>>> 42
42
>>> 42,
(42,)


>>> 3 * (40 + 2)
126
>>> 3 * (40 + 2,)
(42, 42, 42)

第3章 字符串

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

1、格式化

# 1、%
>>> "Hello, %s. %s enough for ya?" % ('world', 'Hot')
'Hello, world. Hot enough for ya?'

# 2、Template $
>>> from string import Template
>>> Template("Hello, $who! $what enough for ya?").substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'

# format 推荐
## 位置
>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'

## 索引可乱序
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'

## 关键字参数:变量名
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.'

## f字符串
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
# format 每个值都被插入字符串中,以替换用花括号括起的替换字段
"""
字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。除指定值外,还可指定值的特定部分,如列表的元素。
"""
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
'3 1 4 2'

>>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
'3 2 4 1'


>>> "Mr {name[1]}".format(name=["Alfred", "Smoketoomuch"])
'Mr Smoketoomuch'

>>> import math
>>> "The {mod.__name__} module defines the value {mod.pi} for π".format(mod=math)
'The math module defines the value 3.141592653589793 for π'


"""
转换标志:跟在叹号后面的单个字符。当前支持的字符包括r(表示repr)、s(表示str)和a(表示ascii)。如果你指定了转换标志,将不使用对象本身的格式设置机制,而是使用指定的函数将对象转换为字符串,再做进一步的格式设置。
"""
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'

>>> "The number is {num}, {num:f}, {num:b}".format(num=42)
'The number is 42, 42.000000, 101010'

## 宽度
>>> "{num:10}".format(num=3)
'         3'
>>> "{name:10}".format(name="Bob")
'Bob       '

## 精度
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14'

>>> "{pi:10.2f}".format(pi=pi)
'      3.14'

>>> "{:.5}".format("Guido van Rossum")
'Guido'

## 千位分隔符
>>> 'One googol is {:,}'.format(10**100)
'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'

"""
格式说明符:跟在冒号后面的表达式(这种表达式是使用微型格式指定语言表示的)。格式说明符让我们能够详细地指定最终的格式,包括格式类型(如字符串、浮点数或十六进制数),字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对齐和填充方式。
"""
>>> '{:010.2f}'.format(pi)
'0000003.14'

## 左对齐、右对齐和居中
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14
   3.14
      3.14

>>> "{:$^15}".format(" WIN BIG ")
'$$$ WIN BIG $$$'

>>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
3.14
-3.14
>>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
      3.14
     -3.14

>>> print('{0:10.2f}\n{1:=10.2f}'.format(pi, -pi))
      3.14
-     3.14


>>> print('{0:-.2}\n{1:-.2}'.format(pi, -pi)) #默认设置
 3.1
-3.1
>>> print('{0:+.2}\n{1:+.2}'.format(pi, -pi))
+3.1
-3.1
>>> print('{0: .2}\n{1: .2}'.format(pi, -pi))
 3.1
-3.1


>>> "{:b}".format(42)
'101010'
>>> "{:#b}".format(42)
'0b101010'

>>> "{:g}".format(42)
'42'
>>> "{:#g}".format(42)
'42.0000'

2、字符串方法

# center通过在两边添加填充字符(默认为空格)让字符串居中。  ljust、rjust和zfill
>>> "The Middle by Jimmy Eat World".center(39)
' The Middle by Jimmy Eat World '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'

# find 在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。  rfind、index、rindex、count、startswith、endswith
>>> 'With a moo-moo here, and a moo-moo there'.find('moo')
7
>>> title = "Monty Python's Flying Circus"
>>> title.find('Python')
6
>>> title.find('Zirquss')
-1

>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1) # 只指定了起点
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
-1


# join 合并序列的元素

>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq) # 尝试合并一个数字列表
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>> seq = ['1', '2', '3', '4', '5']
>>> sep.join(seq) # 合并一个字符串列表
'1+2+3+4+5'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env

# lower、capitalize、casefold、swapcase、title、upper

# replace 指定子串都替换为另一个字符串,并返回替换后的结果
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'

# split 用于将字符串拆分为序列
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']

# strip 将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果; lstrip、rstrip
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'

>>> names = ['gumby', 'smith', 'jones']
>>> name = 'gumby '
>>> if name in names: print('Found it!')
...
>>> if name.strip() in names: print('Found it!')
...
Found it!

>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'

# translate 进行单字符替换;同时替换多个字符
>>> table = str.maketrans('cs', 'kz')
>>> table
{115: 122, 99: 107}
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'

>>> table = str.maketrans('cs', 'kz', ' ')
>>> 'this is an incredible test'.translate(table)
'thizizaninkredibletezt'

# 判断字符串是否满足特定的条件
"""
isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、
isprintable、isspace、istitle、isupper
"""

第4章 字典

  • 字典由键及其相应的值组成,这种键-值对称为项(item)
## 字典
>>> items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}

>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}


"""
len(d)    返回字典d包含的项(键-值对)数。
d[k]      返回与键k相关联的值。
d[k] = v  将值v关联到键k。
del d[k]  删除键为k的项。
k in d    检查字典d是否包含键为k的项。
"""

"""
键的类型:字典中的键可以是任何不可变的类型,如整数、浮点数(实数)、字符串或元组。

自动添加:即便是字典中原本没有的键,也可以给它赋值,这将在字典中创建一个新项。

成员资格:表达式k in d(其中d是一个字典)查找的是键而不是值。
"""

# 通过字典 格式化字符串
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
>>> "Cecil's phone number is {Cecil}.".format_map(phonebook)
"Cecil's phone number is 3258."

# clear删除所有的字典项,就地执行,返回None。
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x = {}
>>> y
{'key': 'value'}
下面是第二个场景:
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{}

## copy返回一个新字典,其包含的键值对与原来的字典相同,浅复制
>>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'baz']}

## deepcopy 深复制
>>> from copy import deepcopy
>>> d = {}
>>> d['names'] = ['Alfred', 'Bertrand']
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfred', 'Bertrand']}

# fromkeys创建一个新字典,其中包含指定的键,且每个键对应的值都是None
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None}

>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}

>>> dict.fromkeys(['name', 'age'], '(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}

## get
>>> d = {}
>>> print(d['name'])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'name'

>>> print(d.get('name'))
None

>>> d.get('name', 'N/A')
'N/A'

## items返回一个包含所有字典项的列表,其中每个元素都为(key, value)的形式(字典视图)。字典项在列表中的排列顺序不确定。
>>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()
dict_items([('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')])
# 字典视图不复制,它们始终是底层字典的反映
>>> it = d.items()
>>> len(it)
3
>>> ('spam', 0) in it
True
>>> d['spam'] = 1
>>> ('spam', 0) in it
False
>>> d['spam'] = 0
>>> ('spam', 0) in it
True

## keys返回一个字典视图,其中包含指定字典中的

## pop可用于获取与指定键相关联的值,并将该键值对从字典中删除。
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}

## popitem 随机地弹出一个字典项
>>> d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
>>> d.popitem()
('url', 'http://www.python.org')
>>> d
{'spam': 0, 'title': 'Python Web Site'}

## setdefault 获取与指定键相关联的值
>>> d = {}
>>> d.setdefault('name', 'N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d['name'] = 'Gumby'
>>> d.setdefault('name', 'N/A')
'Gumby'
>>> d
{'name': 'Gumby'}

## update使用一个字典中的项来更新另一个字典。(字典拼接)

## values返回一个由字典中的值组成的字典视图,可以重复
>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values()
dict_values([1, 2, 3, 1])

第5章 print和import

1、print

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

2、import

import somemodule
from somemodule import somefunction
from somemodule import somefunction, anotherfunction, yetanotherfunction
from somemodule import *
froom module1.module2 import somefunction
import somemodule as othername

3、序列解包

# 可同时(并行)给多个变量赋值
>>> x, y, z = 1, 2, 3
>>> print(x, y, z)
1 2 3

# 交换变量值
>>> x, y = y, x
>>> print(x, y, z)
2 1 3

# 解包
>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1

# 字典解包
>>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
>>> key, value = scoundrel.popitem()
>>> key
'girlfriend'
>>> value
'Marion'

# 序列包含的元素个数必须与你在等号左边列出的目标个数相同

>>> a, b, *rest = [1, 2, 3, 4]
>>> rest
[3, 4]

>>> name = "Albus Percival Wulfric Brian Dumbledore"
>>> first, *middle, last = name.split()
>>> middle
['Percival', 'Wulfric', 'Brian']

>>> a, *b, c = "abc"
>>> a, b, c
('a', ['b'], 'c')


# 链式赋值
x = y = somefunction()  等价于
y = somefunction()
x = y

# 增强赋值
x += 1

4、缩进

5、条件

False None 0 "" () [] {}

bool([]) == bool("") == False

# 链式比较
0 < age < 100

# is    is not    in    not in
# is:相同运算符
# ==用来检查两个对象是否相等,而is用来检查两个对象是否相同(是同一个对象)。
>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False

# in:成员资格运算符

# 字符串和序列的比较
# 字母排列顺序,但字母都是Unicode字符,它们是按码点排列的
>>> "alpha" < "beta"
True

>>> "a" < "B"
False

>>> [1, 2] < [2, 1]
True

>>> [2, [1, 4]] < [2, [1, 5]]
True

# 短路逻辑 and  or   not 

6、断言

# assert 检查点
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError

# 加断言检查异常说明
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: The age must be realistic

6、循环

"""
while、for

"""


for number in range(1,101):
    print(number)

# 无序
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
    print(key, 'corresponds to', d[key])

for key, value in d.items():
    print(key, 'corresponds to', value)

7、迭代工具

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
# 并行迭代
>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]

for name, age in zip(names, ages):
    print(name, 'is', age, 'years old')

# 当序列的长度不同时,函数zip将
# 在最短的序列用完后停止“缝合”。
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

# 迭代时取索引
for index, string in enumerate(strings):
    if 'xxx' in string:
        strings[index] = '[censored]'
# 反向迭代和排序后再迭代
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'

8、跳出循环

break
continue
while True/break
01-06 09:55