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 ...
随机推荐
- Nginx启用Gzip压缩js无效的原因
Nginx启用gzip很简单,只需要设置一下配置文件即可完成,可以参考文章Nginx如何配置Gzip压缩功能.不过,在群里常有人提到,他们的网站Gzip压缩虽然成功了,但检测到JS仍然没有压缩成功,这 ...
- leetcode_No.1 Two Sum
原题: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- CUDA 纹理内存
原文链接 1.概述 纹理存储器中的数据以一维.二维或者三维数组的形式存储在显存中,可以通过缓存加速访问,并且可以声明大小比常数存储器要大的多. 在kernel中访问纹理存储器的操作称为纹理拾取(tex ...
- matlab时间测试
因为想把样本筛选一下,所以简单的分类器先跑了一下,没想到跑完分类器在对样本筛选时的时间大大超过了样本进分类器的时间,这个显然不能达到我要的节省时间目的.于是分析了一下matlab中各个环节的时间成本, ...
- Pop–实现任意iOS对象的任意属性的动态变化
简介 Pop 是一个可扩展的动画引擎,可用于实现任意iOS对象的任意属性的动态变化,支持一般动画,弹性动画和渐变动画三种类型. 项目主页: pop 最新示例: 点击下载 注意: 官方代码中,并不包含实 ...
- poj_1995_Raising Modulo Numbers
Description People are different. Some secretly read magazines full of interesting girls' pictures, ...
- mysql 数据库设计规范
MySQL数据库设计规范 目录 1. 规范背景与目的 2. 设计规范 2.1 数据库设计 2.1.1 库名 2.1.2 表结构 2.1.3 列数据类型优化 2.1.4 索引设计 2.1.5 分库分表. ...
- mysql 自增主键为什么不是连续的?
由于自增主键可以让主键索引尽量地保持递增顺序插入,避免了页分裂,因此索引更紧凑 MyISAM 引擎的自增值保存在数据文件中 nnoDB 引擎的自增值,其实是保存在了内存里,并且到了 MySQL 8.0 ...
- 给网站添加icon图标
只需制成ico结尾的图片即可
- Linux进程通信之匿名管道
进程间的通信方式 进程间的通信方式包括,管道.共享内存.信号.信号量.消息队列.套接字. 进程间通信的目的 进程间通信的主要目的是:数据传输.数据共享.事件通知.资源共享.进程控制等. 进程间通信之管 ...