Python Tricks(python 的一些小技巧)后续会慢慢更新~~~

Python Tricks

一些在编写python的时候可能会用到的一些小技巧,希望大家能够有所收获,我会慢慢更新~~

🤨🤨🤨🤨🤨

1.How to merge two dictionaries(合并两个字典,元组同理)

#合并两个字典
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}
>>> z
{'c': 4, 'a': 1, 'b': 3}
#合并两个元组
>>> x = (1,2,3)
>>> y = ,5(4)

>>> z = (*x, *y)
>>> z
(1,2,3,4,5)
#In Python 2.x you could
#use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}

2.Different ways to test multiple flags at once in Python(一次测试多个条件)

# Different ways to test multiple flags at once in Python
x, y, z = 0, 1, 0

if x == 1 or y == 1 or z == 1:
    print('passed')

if 1 in (x, y, z):
    print('passed')

# These only test for truthiness:
if x or y or z:
    print('passed')

if any((x, y, z)):
    print('passed')

3.How to sort a Python dict by value(根据值对一个字典排序)

# How to sort a Python dict by value(== get a representation sorted by value)

>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Or:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

4.The get() method on Python dicts and its “default” arg(关于字典的get方法和默认值)

# The get() method on dicts and its "default" argument
# get获取字典内的key对应的value时,如果key不存在,则返回第二个参数为默认值

name_for_userid = {
    382: "Alice",
    590: "Bob",
    951: "Dilbert",
}

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

>>> greeting(382)
"Hi Alice!"

>>> greeting(333333)
"Hi there!"

5. Python’s namedtuples can be a great alternative to defining a class manually(命名元祖可以替代手动定义一个类)

# Why Python is Great: Namedtuples Using namedtuple is way shorter than defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')

# Our new "Car" class works as expected:
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4

# We get a nice string repr for free:
>>> my_car
Car(color='red' , mileage=3812.4)

# Like tuples, namedtuples are immutable:值不可更改
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"

6.Try running “import this” inside a Python REPL …

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

7. Use “json.dumps()” to pretty-print Python dicts(使用json.dumps美观的打印一个字典)

# The standard string repr for dicts is hard to read:
>>> my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
>>> my_mapping
{'b': 42, 'c': 12648430. 'a': 23}  # 😞

# The "json" module can do a much better job:
>>> import json
>>> print(json.dumps(my_mapping, indent=4, sort_keys=True))
{
    "a": 23,
    "b": 42,
    "c": 12648430
}

# Note this only works with dicts containing primitive types (check out the "pprint" module):
>>> json.dumps({all: 'yup'})
TypeError: keys must be a string

8.Python’s shorthand for in-place value swapping(交换变量的值)

# Why Python Is Great:
# In-place value swapping

# Let's say we want to swap
# the values of a and b...
a = 23
b = 42

# The "classic" way to do it with a temporary variable:(以往的传统方式)
tmp = a
a = b
b = tmp

# Python also lets us use this short-hand:
a, b = b, a

9.“is” vs “==”(对比is和双=)

# "is" vs "=="

>>> a = [1, 2, 3]
>>> b = a

>>> a is b
True
>>> a == b
True

>>> c = list(a)

>>> a == c
True
>>> a is c
False

# • "is" expressions evaluate to True if two variables point to the same object
is表示的是如果两个变量指向同一个对象,则为True

# • "==" evaluates to True if the objects referred to by the variables are equal
==则是当两个变量相等则为True

10.Functions are first-class citizens in Python(函数也是变量)

# Functions are first-class citizens in Python:

# They can be passed as arguments to other functions, returned as values from other functions, and assigned to variables and stored in data structures.
函数也可以被当作变量来传递给其他函数,也可以被当作值返回,还可以分配给变量并存储在数据结构中.

>>> def myfunc(a, b):
...     return a + b
...
>>> funcs = [myfunc]
>>> funcs[0]
<function myfunc at 0x107012230>
>>> funcs[0](2, 3)
5

11. Dicts can be used to emulate switch/case statements(字典也可以用于模仿switch/case语句)

# Because Python has first-class functions they can be used to emulate switch/case statements

def dispatch_if(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None


def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()


>>> dispatch_if('mul', 2, 8)
16

>>> dispatch_dict('mul', 2, 8)
16

>>> dispatch_if('unknown', 2, 8)
None

>>> dispatch_dict('unknown', 2, 8)
None

12.Python’s list comprehensions are awesome(列表推导式)

# Python's list comprehensions are awesome.

vals = [expression 
        for value in collection 
        if condition]

# 上边的代码和下面的代码等效:

vals = []
for value in collection:
    if condition:
        vals.append(expression)

# Example:

>>> even_squares = [x * x for x in range(10) if not x % 2]
>>> even_squares
[0, 4, 16, 36, 64]

13.Python 3.5+ type annotations(3.5版本以上的python可以使用类型注解)

Python 3.5+支持“类型注释”,可以与Mypy等工具一起使用以编写静态类型的Python:
# Python 3.5+ supports 'type annotations' that can be
# used with tools like Mypy to write statically typed Python:

def my_add(a: int, b: int) -> int:
    return a + b
: int 表示希望该参数传递一个int值,-> int 表示该方法会返回一个int类型的值;

14.Python list slice syntax(python 列表切片)

# Python's list slice syntax can be used without indices
# for a few fun and useful things:

# 从一个列表清除该列表的所有元素:
>>> lst = [1, 2, 3, 4, 5]
>>> del lst[:]
>>> lst
[]

# You can replace all elements of a list without creating a new list object:
你可以不创建新列表对象的去替换一个列表的所有元素
>>> a = lst
>>> lst[:] = [7, 8, 9]
>>> lst
[7, 8, 9]
>>> a
[7, 8, 9]
>>> a is lst
True

# You can also create a (shallow) copy of a list:
>>> b = lst[:]
>>> b
[7, 8, 9]
>>> b is lst
False

14.itertools.permutations()(排列工具函数)

# itertools.permutations() generates permutations for an iterable. Time to brute-force those passwords ;-)
生成一个可迭代对象所有排列的可能,可以暴力破解密码🤪🤪🤪🤪🤪

>>> import itertools
>>> for p in itertools.permutations('ABCD'):
...     print(p)

('A', 'B', 'C', 'D')
('A', 'B', 'D', 'C')
('A', 'C', 'B', 'D')
('A', 'C', 'D', 'B')
('A', 'D', 'B', 'C')
('A', 'D', 'C', 'B')
('B', 'A', 'C', 'D')
('B', 'A', 'D', 'C')
('B', 'C', 'A', 'D')
('B', 'C', 'D', 'A')
('B', 'D', 'A', 'C')
('B', 'D', 'C', 'A')
('C', 'A', 'B', 'D')
('C', 'A', 'D', 'B')
('C', 'B', 'A', 'D')
('C', 'B', 'D', 'A')
('C', 'D', 'A', 'B')
('C', 'D', 'B', 'A')
('D', 'A', 'B', 'C')
('D', 'A', 'C', 'B')
('D', 'B', 'A', 'C')
('D', 'B', 'C', 'A')
('D', 'C', 'A', 'B')
('D', 'C', 'B', 'A')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值