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 ...
随机推荐
- 1.4 NBU配置备份策略(Policy)
1.4 配置备份策略(Policy) 一个备份策略由四部分组成. Attributes(属性) Policy是否Active Policy类型 由此Policy产生的任务的优先级 使用的Storage ...
- 使用Excel管理命令输出
效果图:(饼状图为后添加) 实现代码:
- 20145238-荆玉茗 《Java程序设计》第10周学习总结
20145238 <Java程序设计>第10周学习总结 网络编程 ·网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发送到指定的位置,或者接收到指定 ...
- Maven 配置本地依赖jar
现有json-1.0.jar,引入依赖方法如下: 1. 在项目下新建 lib 目录,复制json-1.0.jar到lib目录下 pom.xml中添加配置 <dependency> < ...
- System.Web.UI.Page
mdsn:点击查看此类介绍 git: 点击查看封装方法 消息弹框,消息弹框跳转,自定义脚本信息 定义:表示一个从托管 ASP.NET Web 应用程序的服务器请求的 .aspx 文件(也称为 ...
- python main
python中的main函数,总体来说就是,main比较适合写test测试,有点类似于java中的testcase,就是程序单独运行时是运行main的,但是当被调用时就不会运行main了.具体可以参考 ...
- js世界这么大,闭包想看看
什么是闭包,为什么要用他?闭包是能够访问其他函数作用域的函数.我们来分析下句子成分(语文大神),闭包是函数,js函数的作用域分为全局作用域,局部作用域,eval作用域,并没有块级作用域形象的讲,每个函 ...
- spring-传统AOP
Spring传统AOP AOP的增强类型 AOP联盟定义了Advice(org.aopalliance.aop.Interface.Advice) 五类(目标类方法的连接点): 1. 前置通知(or ...
- ofbiz研究
近段时间,刚有有时间研究了下ofbiz ; 目前还是刚开始,后期会记录过程 有一起研究的没
- Google Compute Engine VM自动调节
现象:利用google云搭建VM服务,在搭建实例组有一个"自动调节"功能,可以自动添加/删除MV,当自动添加VM时可能新添加的VM就是一个新的VM,你部署的代码或者环境都没了.现在 ...