• 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
    

    参考资料

    1. Pytricks
    2. hidden features in Python
  • 相关阅读:
    【重学计算机】操作系统D5章:文件系统
    【重学计算机】操作系统D4章:设备管理
    【重学计算机】操作系统D3章:存储管理
    【重学计算机】操作系统D2章:处理器管理
    【重学计算机】操作系统D1章:计算机操作系统概述
    【重学计算机】计算机组成原理
    java 图片生成缩略图后,转化成流
    jquery textarea输入字符字数提示
    shell 脚本连接mysql数据库查询database中表的数量和表名
    Maven deploy时报Fatal error compiling: tools.jar not found错误的问题处理
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/6652247.html
Copyright © 2020-2023  润新知