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.1 NBU基本概念
1.1 NBU基本概念 1) Policy(备份策略) 备份策略定义一台或几台服务器的备份方法.它包括哪些服务器需要备份.备份哪些目录或文件.在什么时间备份.采用什么方式进行备份等.配置NBU主要指定 ...
- veritas.com常用资源汇总
NetBackup 8.1.2文档(合集) https://www.veritas.com/support/en_US/article.100044086 NetBackup产品组停止支持生命周期 ...
- input的placeholder的颜色、字号、边距设置
#scbar_txt::-webkit-input-placeholder { /* WebKit browsers */ text-indent: 10px; font-size:16px; ...
- BZOJ3669: [Noi2014]魔法森林(瓶颈生成树 LCT)
Time Limit: 30 Sec Memory Limit: 512 MBSubmit: 3558 Solved: 2283[Submit][Status][Discuss] Descript ...
- js、jquery中全局替换replace
str.replace(/需要替换的/g,"新字符串") //此处使用正则表达式
- Spring框架进阶3
Spring框架进阶3 测试spring_jdbc和spring对事务的管理 先配置相应的pom <?xml version="1.0" encoding="UTF ...
- form表单submit按钮提交页面不跳转
方案一 <html> <body> <form action="" method="post" target="nm_i ...
- python+scrapy环境搭建步骤描述
Python3(3.5.4)搭建爬虫系统步骤描述: 1.下载python安装包,路径:https://www.python.org/downloads/windows/ 选择3.5.4版本64位的安 ...
- GDOI--DAY2 游记
今天,熬夜不够多,果然,不出所料,爆零了... 第一题,看到数据之大,懵逼了,于是,敲了个二分SPFA,但是!最大的点GG了,呜呜~~~~(>_<)~~~~ ,于是,就不继续做第一题了(虽 ...
- linux-shell——02
Linux命令的通用命令格式 :命令字 [选项] [参数] 选项: 作用:用于调节命令的具体功能 "-"引导短格式选项(单个字符) EX:“-l” "--"引导 ...