美文网首页
python的一些骚操作

python的一些骚操作

作者: M_lear | 来源:发表于2018-11-11 11:09 被阅读0次
    1. 交换变量值
    a,b = b,a
    
    1. 将列表中的所有元素组合成字符串
    a = ['Hello', 'world']
    print(" ".join(a))
    
    1. 找出列表中出现频率最大的值
    max(a, key = a.count)
    
    1. 检查两个字符串是不是由相同字母不同顺序组成
    from collections import Counter
    Counter(str1) == Counter(str2)
    
    1. 转置二维列表
    arrayT = zip(*array)
    print(list(arrayT))
    
    1. 链式比较
    3 < b < 7
    
    1. 链式函数调用
    def product(a,b):
        return a*b
    
    def add(a,b):
        return a+b;
    
    (product if count > 20 else add)(5,6)
    
    1. for else
    >>> for i in range(0,10):
            if i > 10:
                break;
        else:
            print "hello world";
    输出:hello world
    

    在for 循环中,如果没有从任何一个break中退出,则会执行和for对应的else
    只要从break中退出了,则else部分不执行。

    1. 合并字典
    {**d1,**d2}
    dict(d1.items() | d2.items())
    d1.update(d2)
    
    1. 列表中最大值的索引
    a.index(max(a))
    
    1. 找出字典中value最大对应的key
    list(d.keys())[list(d.values()).index(max(d.values()))]
    
    1. 字典生成式,关键点是构造元组的列表
    dict([(x,2*x) for x in range(1,6)])
    dict(zip(list(range(1,6)),[3,4,7,6,5]))
    
    list0=[('name','zhagnsan'),('age',22),('phone',110)]
    dict_1={key:value for key,value in list0}
    
    {key:value for key,value in zip([1,2,3],[4,5,6])}
    

    相关文章

      网友评论

          本文标题:python的一些骚操作

          本文链接:https://www.haomeiwen.com/subject/yzlxfqtx.html