博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 黑魔法(持续收录)
阅读量:5283 次
发布时间:2019-06-14

本文共 3909 字,大约阅读时间需要 13 分钟。

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([]))# Falseprint(all([]))# Trueprint(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 * bdef subtract(a, b):    return a - bb = Trueprint((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 itertoolsa = [[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 Python3for ky in dctA.keys() & dctB.keys():    print(ky)# loop over dicts that share (some) keys and values in Python3for 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.5print({**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.7def maxIndex(lst):    return max(range(len(lst)), key=lst.__getitem__)  # use xrange if < 2.7print(minIndex(lst))print(maxIndex(lst))

remove duplicate items from list and keep order

from collections import OrderedDictitems = ["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 listprint("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 defaultdicttree = 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

参考资料

转载于:https://www.cnblogs.com/crackpotisback/p/6652247.html

你可能感兴趣的文章
大数据学习大纲,大数据应该怎么学
查看>>
HTTP协议学习笔记
查看>>
sublime 打开命令窗口监控
查看>>
2014-9-4 技术创业分享汇
查看>>
利用上载漏洞,攻击asp.net 网站
查看>>
Springboot整合Kfka
查看>>
数学·序言
查看>>
jstack 命令介绍
查看>>
Android Studio Tips
查看>>
EM算法的应用
查看>>
STM32 输入捕获配置
查看>>
Spark 运行架构核心总结
查看>>
判断是否有审核的项目(案例)
查看>>
问题,不是逃避的
查看>>
HTML 自学笔记(HTML的图像标记+超链接的使用)
查看>>
Arduino学习笔记40
查看>>
VS2010之– Web Development(三)-使用VisualStudio打包发布WebApplication
查看>>
LeetCode 671. 二叉树中第二小的节点(Second Minimum Node In a Binary Tree) 9
查看>>
scrapy之中间件
查看>>
51Nod 1016 - 水仙花数
查看>>