# NVIDIA工程师小姐姐的Python隐藏技巧合集，推特2400赞，代码可以直接跑

## 隐藏技巧五大类

### 1、Lambda、Map、Filter、Reduce函数

lambda 关键字，是用来创建内联函数 (Inline Functions) 的。square_fn 和 square_ld 函数，在这里是一样的。

def square_fn(x):
return x * x

square_ld = lambda x : x * x

for i in range(10):
assert square_fn(i) == square_ld(i)

lambda 函数可以快速声明，所以拿来当回调 (Callbacks) 函数是非常理想的：就是作为参数 (Arguments) 传递给其他函数用的，那种函数。

map(fn,iterable) 会把 fn 应用在 iterable 的所有元素上，返回一个map object。

nums = [1/3, 333/7, 2323/2230, 40/34, 2/3]
nums_squared = [num * num for num in nums]
print(nums_squared)

==> [0.1111111, 2263.04081632, 1.085147, 1.384083, 0.44444444]

nums_squared_1 = map(square_fn, nums)
nums_squared_2 = map(lambda x : x * x, nums)
print(list(nums_squared_1))

==> [0.1111111, 2263.04081632, 1.085147, 1.384083, 0.44444444]

map 也可以有不止一个 iterable。

a, b = 3, -0.5
xs = [2, 3, 4, 5]
labels = [6.4, 8.9, 10.9, 15.3]

# Method 1: using a loop
errors = []
for i, x in enumerate(xs):
errors.append((a * x + b - labels[i]) ** 2)
result1 = sum(errors) ** 0.5 / len(xs)

# Method 2: using map
diffs = map(lambda x, y: (a * x + b - y) ** 2, xs, labels)
result2 = sum(diffs) ** 0.5 / len(xs)

print(result1, result2)

==> 0.35089172119045514 0.35089172119045514

filter(fn,iterable) 也是和 map 一样道理，只不过 fn 返回的是一个布尔值，filter 返回的是，iterable 里面所有 fn 返回True的元素。

bad_preds = filter(lambda x: x > 0.5, errors)

==> [0.8100000000000006, 0.6400000000000011]

reduce(fn,iterable,initializer) 是用来给列表里的所有元素，迭代地应用某一个算子。比如，想要算出列表里所有元素的乘积：

product = 1
for num in nums:
product *= num
print(product)

==> 12.95564683272412

from functools import reduce
product = reduce(lambda x, y: x * y, nums)
print(product)

==> 12.95564683272412

### 2、列表操作

2.1、解包 (Unpacking)

elems = [1, 2, 3, 4]
a, b, c, d = elems
print(a, b, c, d)

==> 1 2 3 4

elems = [1, 2, 3, 4]
a, b, c, d = elems
print(a, b, c, d)

==> 1 2 3 4

2.2、切片 (Slicing)

elems = list(range(10))
print(elems)

==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(elems[::-1])

==> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

evens = elems[::2]
print(evens)

reversed_evens = elems[-2::-2]
print(reversed_evens)

==> [0, 2, 4, 6, 8]
[8, 6, 4, 2, 0]

del elems[::2]
print(elems)

==> [1, 3, 5, 7, 9]

2.3、插入 (Insertion)

elems = list(range(10))
elems[1] = 10
print(elems)

==> [0, 10, 2, 3, 4, 5, 6, 7, 8, 9]

elems = list(range(10))
elems[1:2] = [20, 30, 40]
print(elems)

==> [0, 20, 30, 40, 2, 3, 4, 5, 6, 7, 8, 9]

elems = list(range(10))
elems[1:1] = [0.2, 0.3, 0.5]
print(elems)

==> [0, 0.2, 0.3, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2.4、拉平 (Flattening)

list_of_lists = [[1], [2, 3], [4, 5, 6]]
sum(list_of_lists, [])

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

nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
flatten(nested_lists)

# This line of code is from
# https://github.com/sahands/python-by-example/blob/master/python-by-example.rst#flattening-lists

2.5、列表vs生成器

tokens = ['i', 'want', 'to', 'go', 'to', 'school']

def ngrams(tokens, n):
length = len(tokens)
grams = []
for i in range(length - n + 1):
grams.append(tokens[i:i+n])
return grams

print(ngrams(tokens, 3))

==> [['i', 'want', 'to'],
['want', 'to', 'go'],
['to', 'go', 'to'],
['go', 'to', 'school']]

def ngrams(tokens, n):
length = len(tokens)
for i in range(length - n + 1):
yield tokens[i:i+n]

ngrams_generator = ngrams(tokens, 3)
print(ngrams_generator)

==> <generator object ngrams at 0x1069b26d0>

for ngram in ngrams_generator:
print(ngram)

==> ['i', 'want', 'to']
['want', 'to', 'go']
['to', 'go', 'to']
['go', 'to', 'school']

def ngrams(tokens, n):
length = len(tokens)
slices = (tokens[i:length-n+i+1] for i in range(n))
return zip(*slices)

ngrams_generator = ngrams(tokens, 3)
print(ngrams_generator)

==> <zip object at 0x1069a7dc8> # zip objects are generators

for ngram in ngrams_generator:
print(ngram)

==> ('i', 'want', 'to')
('want', 'to', 'go')
('to', 'go', 'to')
('go', 'to', 'school')

[] 返回的是列表，() 返回的是生成器。

### 3、类，以及魔术方法

class Node:
""" A struct to denote the node of a binary tree.
3    It contains a value and pointers to left and right children.
4    """
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right

root = Node(5)
print(root) # <__main__.Node object at 0x1069c4518>

class Node:
""" A struct to denote the node of a binary tree.
3    It contains a value and pointers to left and right children.
4    """
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right

def __repr__(self):
strings = [f'value: {self.value}']
strings.append(f'left: {self.left.value}' if self.left else 'left: None')
strings.append(f'right: {self.right.value}' if self.right else 'right: None')
return ', '.join(strings)

left = Node(4)
root = Node(5, left)
print(root) # value: 5, left: 4, right: None

class Node:
""" A struct to denote the node of a binary tree.
3    It contains a value and pointers to left and right children.
4    """
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right

def __eq__(self, other):
return self.value == other.value

def __lt__(self, other):
return self.value < other.value

def __ge__(self, other):
return self.value >= other.value

left = Node(4)
root = Node(5, left)
print(left == root) # False
print(left < root) # True
print(left >= root) # False

class Node:
""" A struct to denote the node of a binary tree.
3    It contains a value and pointers to left and right children.
4    """
__slots__ = ('value', 'left', 'right')
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right

### 4、局部命名空间，对象的属性

locals() 函数，返回的是一个字典 (Dictionary) ，它包含了局部命名空间 (Local Namespace) 里定义的变量。

class Model1:
def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):
print(locals())
self.hidden_size = hidden_size
self.num_layers = num_layers
self.learning_rate = learning_rate

model1 = Model1()

==> {'learning_rate': 0.0003, 'num_layers': 3, 'hidden_size': 100, 'self': <__main__.Model1 object at 0x1069b1470>}

print(model1.__dict__)

==> {'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}

class Model2:
def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):
params = locals()
del params['self']
self.__dict__ = params

model2 = Model2()
print(model2.__dict__)

==> {'learning_rate': 0.0003, 'num_layers': 3, 'hidden_size': 100}

class Model3:
def __init__(self, **kwargs):
self.__dict__ = kwargs

model3 = Model3(hidden_size=100, num_layers=3, learning_rate=3e-4)
print(model3.__dict__)

==> {'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}

https://github.com/chiphuyen/python-is-cool

## 传送门

Notebook传送门： https://github.com/chiphuyen/python-is-cool/blob/master/cool-python-tips.ipynb

0 条评论

• ### 干货 | 32个常用Python功能实现，菜鸟到高手的进阶之路！

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13；特别指出：第0项是0，第1项是第一个1。从第三项开始，每一项都等于前两项之和。

• ### 利用Python让你的命令行像坤坤一样会打篮球

承接上文，作为一个经常逛b站的肥宅，近期b站上除了流行"品如”素材的视频，更多的莫过于蔡xx打球视频的了，有模仿的，有对比的，有手绘的，更过分的是竟然有人在命令...

• ### 100天搞定机器学习|Day16 通过内核技巧实现SVM

再简单回顾一下svm算法的思路，详细推导请看前情回顾相关内容，或在文末下载之前推荐的《理解SVM 的三层境界》PDF版。

• ### 英伟达小姐姐的Python隐藏技巧合集，推特2400赞，代码可以直接跑

常常发资源的英伟达工程师小姐姐Chip Huyen，又发射了一套Python隐藏功能合集。

• ### 英伟达小姐姐开源 Python 隐藏技巧，上了 GitHub 热榜！

转自量子位，作者栗子 常常发资源的英伟达工程师小姐姐 Chip Huyen，又发射了一套 Python 隐藏功能合集。

• ### 英伟达小姐姐的Python隐藏技巧合集，推特2400赞，代码可以直接跑

常常发资源的英伟达工程师小姐姐Chip Huyen，又发射了一套Python隐藏功能合集。

• ### (二十七) 初遇python OOP面向对象编程-继承

各位读者大大们大家好，今天学习python的面向对象编程-继承，并记录学习过程欢迎大家一起交流分享。

• ### Python操作Mysql类

#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb from warnings import fi...

查看源代码 tensorflow/python/framework/ops.py：