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

参考资料

  1. Pytricks
  2. hidden features in Python

Python 黑魔法(持续收录)的更多相关文章

  1. flow.ci + Github + Slack 一步步搭建 Python 自动化持续集成

    理想的程序员必须懒惰,永远追随自动化法则.Automating shapes smarter future. 在一个 Python 项目的开发过程中可能会做的事情:编译.手动或自动化测试.部署环境配置 ...

  2. Python 黑魔法 --- 描述器(descriptor)

    Python 黑魔法---描述器(descriptor) Python黑魔法,前面已经介绍了两个魔法,装饰器和迭代器,通常还有个生成器.生成器固然也是一个很优雅的魔法.生成器更像是函数的行为.而连接类 ...

  3. (转)Python黑魔法 --- 异步IO( asyncio) 协程

    转自:http://www.jianshu.com/p/b5e347b3a17c?from=timeline Python黑魔法 --- 异步IO( asyncio) 协程 作者 人世间 关注 201 ...

  4. python 黑魔法 ---上下文管理器(contextor)

    所谓上下文 计算机上下文(Context)对于我而言,一直是一个很抽象的名词.就像形而上一样,经常听见有人说,但是无法和现实认知世界相结合. 最直观的上下文,莫过于小学的语文课,经常会问联系上下文,推 ...

  5. python黑魔法之metaclass

    最近了解了一下python的metaclass,在学习的过程中,把自己对metaclass的理解写出来和大家分享. 首先, metaclass 中文叫元类,这个元类怎么来理解呢.我们知道,在Pytho ...

  6. Jenkins +git +python 进行持续集成进行接口测试(接口测试jenkins持续集成篇)

    使用jenkins+git+python脚本进行持续集成的接口测试,在jenkins平台,利用插件等,把管理代码的git仓库的代码更新下来进行持续接口测试,python进行开发测试脚本,git进行远程 ...

  7. python 黑魔法收集--已结

    awesome python 中文大全 Fabric , pip, virtualenv 内建函数好文 awesome python 奇技淫巧 一句话求阶乘 from functools import ...

  8. 转--python 黑魔法2

    Python 高效编程小技巧 个人博客:临风|刀背藏身 Python 一直被我拿来写算法题,小程序,因为他使用起来太方便了,各种niubi闪闪的技能点也在写算法的过程中逐渐被挖掘到,感谢万能的谷哥度娘 ...

  9. Python奇技淫巧 - 持续更新中....

    Python奇技淫巧 人生苦短,我用Python: 编程界这绝对不是一句空话,尤其是对于使用过多个语言进行工作的同学们来说,用Python的时间越长,越有一种我早干嘛去了的想法,没事,啥时候用Pyth ...

随机推荐

  1. spring boot1.5.6 测试类1

    package com.example.demo; import org.junit.Before;import org.junit.Test; import org.junit.runner.Run ...

  2. Spring 学习之依赖注入

    什么是依赖关系? 纵观所有的Java 应用,从基于Applet的小应用到多层次结构的企业级别的应用,他们都是一种典型的依赖性应用,也就是由一些互相协作的对象构成的,Spring把这种互相协作的关系称之 ...

  3. es6-promise.auto.js

    使用sweetalert2的IE浏览器报错,导入文件 链接:https://pan.baidu.com/s/1mOcsN_o8m-7I7Rej1NPkiw 提取码:9xsj

  4. Linux下文件的压缩与解压缩

    一.zip格式 zip可能是目前使用的最多的文档压缩格式.它最大的优点就是在不同的操作系统平台上使用.缺点就是支持 的压缩率不是很高,而tar.gz和tar.bz2在压缩率方面做得非常好. 我们可以使 ...

  5. springMVC-数据绑定

    定义: 将http请求中参数绑定到Handler业务方法 常用数据绑定类型 1.  基本数据类型 不能为其它类型和null值 2.  包装类 可以为其它对象,全部转成null值 3.  数组 多个对象 ...

  6. 局域网内使用ssh连接两台计算机总结

    因为家里有两台电脑,一个centos7 系统,一个Mac,都是笔记本,感觉两个拿来拿去的用太麻烦了,所以就想用ssh连接cenots7 的电脑,这样就没那么麻烦了.欢迎大家指正 配置静态ip cent ...

  7. 《Redis设计与实现》- 复制

    在分布式系统中为了解决单点问题,通常会把数据复制多个副本部署到其他机器,满足故障恢复和负载均衡灯需求.Redis提供了复制功能,实现了相同数据多个副本,复制功能作是高可用Redis的基础,深入理解复制 ...

  8. 【转载】java 客户端链接不上redis解决方案 (jedis)

    本文出自:http://blog.csdn.net/lulidaitian/article/details/51946169 出现问题描述: 1.Could not get a resource fr ...

  9. urllib使用三--urlretrieve下载文件

    下载文件 urllib.urlretrieve() 参数: url:远程地址 filename:要保存到本地的文件 reporthook:下载状态报告 data:有就变成POST请求,有格式要求 返回 ...

  10. 笔记-scrapy-辅助功能

    笔记-scrapy-辅助功能 1.      scrapy爬虫管理 爬虫主体写完了,要部署运行,还有一些工程性问题: 限频 爬取深度限制 按条件停止,例如爬取次数,错误次数: 资源使用限制,例如内存限 ...