Python 黑魔法(持续收录)
Python 黑魔法(持续收录)
zip 对矩阵进行转置
a = [[1, 2, 3], [4, 5, 6]]
print(list(map(list, zip(*a))))
zip 反转字典
a = dict(a=1, b=2, c=3)
print(dict(zip(a.values(), a.keys())))
将list分成n份
print(list(zip(*(iter([1, 2, 3, 4, 5, 6]),) * 3)))
# [(1, 2, 3), (4, 5, 6)]
all & any 函数
- all:如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False
- any: 如果所有元素中有一个值不是0、''或False,那么结果就为True,否则为False
print(any([]))
# False
print(all([]))
# True
print(all([1,2,3,0]))
# False
Concatenate long strings elegantly across line breaks in code
my_long_text = ("We are no longer the knights who say Ni! "
"We are now the knights who say ekki-ekki-"
"ekki-p'tang-zoom-boing-z'nourrwringmm!")
print(my_long_text)
# We are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!
calling different functions with same arguments based on condition
def product(a, b):
return a * b
def subtract(a, b):
return a - b
b = True
print((product if b else subtract)(1, 1))
Sort dict keys by value
d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1}
print(sorted(d, key=d.get))
# ['rotten tomato', 'banana', 'apple', 'orange']
exec
exec("print('Hello ' + s)", {'s': 'World!'})
# exec can be used to execute Python code during runtime variables can be handed over as a dict
unpacking
[(c, *d, [*e]), f, *g] = [[1, 2, 3, 4, [5, 5, 5]], 6, 7, 8]
print(c, d, e, f, g)
# 1 [2, 3, 4] [5, 5, 5] 6 [7, 8]
flatten list
import itertools
a = [[1, 2], [3, 4], [[5,6],[7,8]]]
print(list(itertools.chain(*a)))
# [1, 2, 3, 4, [5, 6], [7, 8]]
把嵌套的也flatten?
a = [[1, 2], [3, 4], [[5, 6], [7, 8]]]
a = eval('[%s]' % repr(a).replace('[', '').replace(']', ''))
print(a)
# [1, 2, 3, 4, 5, 6, 7, 8]
更简单?
a = [[1, 'a', ['cat'], 2], [[[3], 'a', 'm', [1, 2, 3], [1, [1, 2, 3]]]], 'dog']
flatten = lambda L: eval(str(L).replace('[', '*[')[1:])
flatten(a)
dict求交
dctA = {'a': 1, 'b': 2, 'c': 3}
dctB = {'b': 4, 'c': 3, 'd': 6}
# loop over dicts that share (some) keys in Python3
for ky in dctA.keys() & dctB.keys():
print(ky)
# loop over dicts that share (some) keys and values in Python3
for item in dctA.items() & dctB.items():
print(item)
split a string max times
"""split a string max times"""
string = "a_b_c"
print(string.split("_", 1))
# ['a', 'b_c']
"""use maxsplit with arbitrary whitespace"""
s = "foo bar foobar foo"
print(s.split(None, 2))
# ['foo', 'bar', 'foobar foo']
字典合并
d1 = {'a': 1}
d2 = {'b': 2}
# python 3.5
print({**d1, **d2})
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1)
Find Index of Min/Max Element
lst = [40, 10, 20, 30]
def minIndex(lst):
return min(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7
def maxIndex(lst):
return max(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7
print(minIndex(lst))
print(maxIndex(lst))
remove duplicate items from list and keep order
from collections import OrderedDict
items = ["foo", "bar", "bar", "foo"]
print(list(OrderedDict.fromkeys(items).keys()))
set global variables from dict
def foo():
d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]}
globals().update(d)
foo()
print(a, b, c)
Sort a list and store previous indices of values
l = [4, 2, 3, 5, 1]
print("original list: ", l)
values, indices = zip(*sorted((a, b) for (b, a) in enumerate(l)))
# now values contains the sorted list and indices contains
# the indices of the corresponding value in the original list
print("sorted list: ", values)
print("original indices: ", indices)
# note that this returns tuples, but if necessary they can
# be converted to lists using list()
None
from collections import defaultdict
tree = lambda: defaultdict(tree)
users = tree()
users['harold']['username'] = 'chopper'
users['matt']['password'] = 'hunter2'
for_else 跳出多层循环
for i in range(5):
for j in range(6):
print(i * j)
if i * j == 20:
break
else:
continue
break
参考资料
Python 黑魔法(持续收录)的更多相关文章
- flow.ci + Github + Slack 一步步搭建 Python 自动化持续集成
理想的程序员必须懒惰,永远追随自动化法则.Automating shapes smarter future. 在一个 Python 项目的开发过程中可能会做的事情:编译.手动或自动化测试.部署环境配置 ...
- Python 黑魔法 --- 描述器(descriptor)
Python 黑魔法---描述器(descriptor) Python黑魔法,前面已经介绍了两个魔法,装饰器和迭代器,通常还有个生成器.生成器固然也是一个很优雅的魔法.生成器更像是函数的行为.而连接类 ...
- (转)Python黑魔法 --- 异步IO( asyncio) 协程
转自:http://www.jianshu.com/p/b5e347b3a17c?from=timeline Python黑魔法 --- 异步IO( asyncio) 协程 作者 人世间 关注 201 ...
- python 黑魔法 ---上下文管理器(contextor)
所谓上下文 计算机上下文(Context)对于我而言,一直是一个很抽象的名词.就像形而上一样,经常听见有人说,但是无法和现实认知世界相结合. 最直观的上下文,莫过于小学的语文课,经常会问联系上下文,推 ...
- python黑魔法之metaclass
最近了解了一下python的metaclass,在学习的过程中,把自己对metaclass的理解写出来和大家分享. 首先, metaclass 中文叫元类,这个元类怎么来理解呢.我们知道,在Pytho ...
- Jenkins +git +python 进行持续集成进行接口测试(接口测试jenkins持续集成篇)
使用jenkins+git+python脚本进行持续集成的接口测试,在jenkins平台,利用插件等,把管理代码的git仓库的代码更新下来进行持续接口测试,python进行开发测试脚本,git进行远程 ...
- python 黑魔法收集--已结
awesome python 中文大全 Fabric , pip, virtualenv 内建函数好文 awesome python 奇技淫巧 一句话求阶乘 from functools import ...
- 转--python 黑魔法2
Python 高效编程小技巧 个人博客:临风|刀背藏身 Python 一直被我拿来写算法题,小程序,因为他使用起来太方便了,各种niubi闪闪的技能点也在写算法的过程中逐渐被挖掘到,感谢万能的谷哥度娘 ...
- Python奇技淫巧 - 持续更新中....
Python奇技淫巧 人生苦短,我用Python: 编程界这绝对不是一句空话,尤其是对于使用过多个语言进行工作的同学们来说,用Python的时间越长,越有一种我早干嘛去了的想法,没事,啥时候用Pyth ...
随机推荐
- ImportError: No module named images
[问题] 在使用学习wxPython时,一个Dem抱有如题所示错误 [解决] images 只不过是wxpython自带demo中的一个文件 体验wxpython IN action的时候Import ...
- svn更改地址怎么办
开发过程中有时会遇到服务器更换地址的情况,比如之前地址是 svn://www.aaa.com 后来换成了 svn://www.bbb.com 这时候怎么办呢?分客户端和服务器端2种情况处理 客户端: ...
- keyframes 放大缩小动画
本次项目中动画放大缩小代码小结 .fix .phone{ -moz-animation: myfirst 1s infinite; -webkit-animation: myfirst 1s infi ...
- ios统计流量代码
#include <ifaddrs.h> #include <sys/socket.h> #include <net/if.h> 1.3G/GPRS流量统计 int ...
- Mysql查看锁等信息SQL语句
查看锁等信息,包括锁信息: select "HOLD:",ph.id h_processid,trh.trx_id h_trx_id,trh.trx_started h_start ...
- 在React Native中集成热更新
最近,在项目DYTT集成了热更新,简单来说,就是不用重新下载安装包即可达到更新应用的目的,也不算教程吧,这里记录一下. 1.热更新方案 目前网上大概有两个比较广泛的方式,分别是 react-nativ ...
- px与em的区别,权重的优先级
px与em的区别,权重的优先级 PX特点:px像素(Pixel).相对长度单位.像素px是相对于显示器屏幕分辨率而言的.EM特点:1. em的值并不是固定的:2. em会继承父级元素的字体大小. 权重 ...
- 关于对GitHub的使用
什么是GitHub? GitHub是版本控制和协作的代码托管平台.它可以让你在其他人在任何地方一起工作. 本文主要向您介绍GitHub essentials,如存储库,分支,提交和合并请求.将您创建自 ...
- POJ:3061-Subsequence(尺取法模板详解)
Subsequence Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 18795 Accepted: 8043 Descript ...
- 13-在Core Mvc中使用Options
配制文件appsettings和Classes来自12节 在HomeController增加如下代码,使用IOption方式进行注入 public class HomeController : Con ...