代码结构

迭代

for迭代

列表、字符串、元组、字典、集合都是可迭代对象。

对一个字典进行迭代将会返回字典中的键。如果想对字典的值进行迭代,可以使用字典的values()函数:

for value in example_dict.values():

而如果想返回(key: value)的元组形式,则可以使用字典的items()函数:

for item in example_dict.items():
    print(item) # (key: value)
enumerate创建迭代器

对于list,for..in..循环只能迭代value,无法或许index。此时,可以通过enumerate创建一个迭代器:

example_list = [1, 2, 3]
for index, value in enumerate(example_list):
    print(index, ':', value)
# 0 : 1
# 1 : 2
# 2 : 3

enumerate还可以接受第二个参数,表示index的起始值:

example_list = [1, 2, 3]
for index, value in enumerate(example_list, 1):
    print(index, ':', value)
# 1 : 1
# 2 : 2
# 3 : 3
zip()

该函数可以遍历多个序列,在具有相同位移的项之间创建元组

list1 = [1, 2, 3, 4]
tuple1 = [a, b, c, d]
list(zip(list1, tuple1)) # [(1, a), (2, b), (3, c), (4, d)]

zip()生成的结果既不是列表也不是元组,而是一个整合在一起的可迭代变量。可通过list()dict()等方法进一步处理

dict(zip('ab', range(2))) # {'a': 0, 'b': 1}

# 压缩与解压缩
tuple_1 = ('a', 'b', 'c')
tuple_2 = (1, 2, 3)

zip_1 = zip(tuple_1, tuple_2) # [('a', 1), ('b', 2), ('c', 1)]
zip_2 = zip(*zip_1) # [('a', 'b', 'c'), (1, 2, 3)]

# 用zip反转dict
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
m.items() # [('a', 1), ('c', 3), ('b', 2), ('d', 4)]
zip(m.values(), m.keys()) # [(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
m_reverse = dict(zip(m.values(), m.keys())) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
range(start, end, step)

返回在特定区间的自然数序列,生成的是一个可循环对象

list(range(2, -1, -1)) # [2, 1, 0]
list(range(0, 11, 2)) # [0, 2, 4, 6, 8, 10]
map()

map(fun, sequence[, sequence...]) 根据提供的函数对指定序列做映射,返回一个可迭代对象

x = map(lambda x: x * 2, [1, 2, 3, 4])
for i in x:
    print(i)
# 2
# 4
# 6
# 8

def abc(a, b, c):
    return a * 100 + b * 10 + c

list1 = [9, 8, 7]
list2 = [9, 8, 7]
list3 = [9, 8, 7]

for i in map(abc, list1, list2, list3):
    print(i)
# 999
# 888
# 777
# map不仅仅可以接受变量参数list,也可以接受函数list

def multiply(x):
    return x * x

def add(x):
    return x + x

funs = [multiply, add]
for i in range(5):
    value = map(lambda x: x(i), funs)
    print(list(value))

# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
filter()

filter(fun, sequence) 第一个参数为函数,接收一个参数并返回一个布尔值

def larger_than_ten(a):
    return a > 10

list1 = [10, 11, 9, 8, 7]

for i in filter(larger_than_ten, list1):
    print(i)
# 11

记一个坑:

filter返回一个filter对象,该对象可以被for迭代,或者通过list()转换为列表

reduce()
from functools import reduce
reduce(fun, sequence[, initial])
# fun是一个接收两个参数的函数
# 提供initial参数,会以sequence中的第一个元素和initial作为参数调用fun
from functools import reduce

def add(x, y):
    return x + y

list1 = [1, 2, 3, 4]
result = reduce(add, list1)
print(result)
# 10
result2 = reduce(add, list1, 10)
print(result2)
# 20

列表推导式

[expression for item in iterable if condition]

expression为符合condition条件的列表生成值。e.g.

# example_1
number_list = [number for number in range(1, 6) if number % 2 == 1]
print(number_list) # [1, 3, 5]

# example_2
# 嵌套列表推导式
rows = range(1, 4)
cols = range(1, 3)
cells = [(row, col) for row in rows for col in cols]
# by the way, for row...和for col...都可以有自己的if判断
print(cells) # [(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]

字典推导式

{key_expression: value_expression for expression in iterable if condition}

word = 'letter'
letter_counts = {letter: word.count(letter) for letter in set(word)}
# 在set(word)中遍历,避免了重复元素的遍历
print(letter_counts) # {'r': 1, 'l': 1, 't': 2, 'e': 2}

集合推导式

{expression for expression in iterable if condition}

new_set = {number for number in range(1, 6) if number % 3 == 1}
print(new_set) # {1, 4}

条件表达式

a = x if True else y

# 一个阶乘函数的递归版本
def factorial(n):
    return 1 if n == 0 else n * factorial(n-1)

# 用条件表达式处理默认参数
def fun(params=None):
    params = params if params != None else 1
    print(params)

fun() # 1

by the way,提一句for...else

# else 语句块会在循环结束后执行,除非在循环块中执行 break
# 即如果for循环中break了,则不会执行for后面紧跟的else
for i in (1, 4, 5):
    if i % 2 == 0:
        break
else:
    print("var i is always an odd")

生成器表达式

生成器表达式与列表推导式类似,但是使用的是圆括号,而不是方括号

g = (x for x in range(4))

print(next(g)) # 0
print(next(g)) # 1

列表推导式&生成器表达式

列表推导也可能会有一些负面效应,那就是整个列表必须一次性加载于内存之中。虽然对大多数情况这都不是问题,但是总会达到极限,内存总会被用完。 针对上面的问题,生成器能够很好的解决。生成器表达式不会一次将整个列表加载到内存之中,而是生成一个生成器对象(Generator objector),所以一次只加载一个列表元素

num = [1, 4, -5, 10, -7, 2, 3, -1]
double_result_g = ( x*2 for x in num if x > 0 )
print(double_result_g)
# <generator object <genexpr> at 0x00583E18>

for item in double_result_g:
    print(item)
# 2
# 8
# 20
# 4
# 6

try/except/else/finally

example = 1

try:
    print('1' + example)
except TypeError as e:
    print(e)
else: 
    # 当没有catch到except的时候走else
    # else语句必须在finally之前
    print('no except')
finally:
    print('finally')

else语句的存在必须以except X或者except语句为前提,如果在没有except语句的try block中使用else语句会引发语法错误

any & all

  • any:接受一个布尔值序列,如果其中有任意一个值为 True 则返回 True
  • all:如果序列中的每个元素均为 True 才会返回 True
has_greater_than_ten = any(i > 10 for i in range(11))
print(has_greater_than_ten) # False

has_greater_than_ten = any(i > 10 for i in range(12))
print(has_greater_than_ten) # True

results matching ""

    No results matching ""