美文网首页
有用的python代码片段

有用的python代码片段

作者: 小毛同学 | 来源:发表于2018-03-29 11:14 被阅读115次

    打印菱形

    • 法1:
    n = 4
    for i in range(2*n-1):
        if i < n:
            number = 2 * i +1
        else:
           number = 2*(2*n-1-i)-1
        print(('*' * number).center(2*n-1, " "))
    
    • 法2(装逼用的):
    n = 4
    _max = 2 * n - 1
    a = [("*"*e).center(_max," ")for e in [2*i - 1 if i<=n else 4*n-2*i-1 for i in range(1, _max+1)]]
    for each in a:
        print(each)
    

    获取一个目录下最新的文件

    import os
    filelist = os.listdir(path)
    filelist.sort(key = lambda fn: os.path.getmtime(os.path.join(path, fn)))
    filelist[-1]   #path目录下最新的文件名
    

    同时遍历list元素和下标

    myList = ["one", "two", "three"]
    
    for i,v in enumerate(myList):
        print(i, v)
    

    发送各种类型邮件

    import smtplib
    import sys
    
    _user = "xxxxx@xxxx.cn"
    _pwd = "xxxxxx"
    
    
    # jpg类型附件
    part = MIMEApplication(open('foo.jpg', 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="foo.jpg")
    msg.attach(part)
    # pdf类型附件
    part = MIMEApplication(open('foo.pdf', 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="foo.pdf")
    msg.attach(part)
    # mp3类型附件
    part = MIMEApplication(open('foo.mp3', 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="foo.mp3")
    msg.attach(part)
    
    def sendEmail(sender, receiver, msg):
        s = smtplib.SMTP("smtp.ym.163.com", 25, timeout=30)  # 连接smtp邮件服务器,端口默认是25
        s.login(_user, _pwd)  # 登陆服务器
        s.sendmail(sender, receiver, msg.as_string())  # 发送邮件
        s.close()
    

    日志配置

    import logging
    
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    

    筛选列表中的数据

    • 列表解析
    from random import randint
    
    data = [randint(-10,10) for _ in range(10)]
    data_after=[x for x in data if x > 0]
    
    • filter函数
    from random import randint
    
    data = [randint(-10,10) for _ in range(10)]
    data_after=list(filter(lambda x:x > 0, data))
    

    筛选字典中的数据

    • 字典解析
    from random import randint
    
    d = {x: randint(60,100) for x in range(1,21)}
    d_after = {k:v for k,v in d.items() if v > 90}
    

    列表去重

    ids = [1,4,3,3,4,2,3,4,5,6,1]
    ids = list(set(ids))
    

    使用命名元组为每个元素命名

    from collections import namedtuple
    Student = namedtuple('Student', ['name', 'age', 'sex'])
    s = Student('aaa',18,"male")
    s2= Student(name='bbb', age=12, sex="female")
    
    if s.name == "aaa":
        pass
    

    统计一个list中各个元素出现的次数

    • 方法1,使用字典
    from random import randint
    data = [randint(1,10) for _ in rang(10)]
    # 把data里的数据作为key来创建一个字典,且value初始化为0
    dic = dict.fromkeys(data, 0)
    for x in data:
       dic[x] += 1   
    #dic 中key为元素,value为该元素出现次数
    
    • 方法2,使用Counter()
    from collections import Counter()
    
    data = [randint(1,10) for _ in range(10)]
    # 得到的dic2和方法1的dic一样,一条代码解决问题!
    dic2 = Counter(data)
    # 并且还可以使用most_common(n)方法来直接统计出出现频率最高的n个元素
    dic2.most_common(2)
    # 输出一个list ,其中的元素为(key,value)的键值对,类似[(6, 4), (3, 2)]这样
    

    对字典排序

    #以上一例子的dic作为排序对象
    dic = {0: 1, 2: 2, 4: 4, 6: 1, 7: 1, -6: 1}
    dic_after = sorted(dic.items(), key=lambda x:x[1])
    # 如果想按key来排序则sorted(dic.items(), key=lambda x:x[0])
    # dic_after为一个列表: [(0, 1), (6, 1), (7, 1), (-6, 1), (2, 2), (4, 4)]
    
    

    使用正则表达式分割文本

    import re
    with open("file.txt") as f
        text = f.read()
    # 分割为所有单词组成的list, \W匹配非字母数字及下划线
    result = re.split('\W+', text)
    

    使用正则表达式提取文本

    import re
    #用(?P<year>...)括住一个群,并命名为year
    m = re.search("output_(?P<year>\d{4})", "output_1986.txt")
    print(m.group("year") #输出1986
    

    启动一个简单的目录服务

    $ cd ~/tmp
    $ python -m SimpleHTTPServer  [port]
    or
    $ python3 -m http.server  [port]
    

    字符串转换为JSON

    $ echo '{"job": "developer", "name": "lmx", "sex": "male"}' | python -m json.tool
        {
            "job": "developer",
            "name": "lmx",
            "sex": "male"
        }
    

    检查三方库是否正确安装

    $ python -c "import paramiko"
    

    使用Python解压zip压缩包

    • -l <zipfile> 显示zip格式压缩包中的文件列表
    • -c 创建zip格式压缩包
    • -e 提取zip格式压缩包
    • -t 验证文件是一个有效的zip格式压缩包
    python -m zipfile -c monty.zip spam.txt eggs.txt
    python -m zipfile -e monty.zip target-dir/
    python -m zipfile -l monty.zip
    

    使用pickle存储对象

    • 使用pickle的dumps()方法可以将对象转换成字符串形式,随后用字节文本形式存储对象到文件
    import pickle
    
    class Bird(object):
        have_feather = True
        
    summer = Bird()
    pickle_string = pickle.dumps(summer)
    
    with open("summer.pkl", "wb") as f:
        f.write(pickle_string)
    

    也可以使用dump方法一步到位

    import pickle
    
    class Bird(object):
        have_feather = True
        
    summer = Bird()
    with open("summer.pkl", "w") as f:
        pickle.dump(summer, f)
    

    使用装饰器计算函数运行时间

    def decorator_timer(foo):
            def wrapper(*arg, **karg):
                t1 = time.time()
                result = foo(*arg, **karg)
                t2 = time.time()
                print(pre+"time:", t2 - t1)
                return result
            return wrapper
            
    @decorator_timer("@_@")
    def my_power(a, b):
        return a**b
        
    print(my_power(2,3))
    #输出:
    #time: 0.0
    #5
    
    

    使用groupby将列表元素分类

    from itertools import groupby
    
    def height_class(h):
        if h> 180:
            return "tall"
        elif h<160:
            return "short"
        else:
            return "middle"
        
    friends = [191,144,142,170,177,188,293]
    friends = sorted(friends, key = height_class)
    for m, n in itertools.groupby(friends, key=height_class):
        print(m)
        print(list(n))
    #middle
    #[170, 177]
    #short
    #[144, 142]
    #tall
    #[191, 188, 293]
    
    

    使用sets计算交集和差集

    set1 = {1,2,3,4}
    set2 = {3,4,5,6}
    
    set1.intersection(set2)#交集
    set1.difference(set2)#差集
    
    

    确保python3中不会使用过期的python2内置功能

    python2中有12个内置功能在Python3中已经被移除了。要确保在Python2代码中不要出现这些功能来保证对Python3的兼容。这有一个强制让你放弃12内置功能的方法:

    from future.builtins.disabled import *
    

    使用正则多个分隔符分割字符串

    import re
    s = "ab,wer.wer,wer|wer||,wwer wer,wer3"
    re.split(r"[,.|]+", s)
    Out[6]: ['ab', 'wer', 'wer', 'wer', 'wer', 'wwer wer', 'wer3']
    

    正则 调整文本格式

    import re
    s = "1991-02-28"
    re.sub(r"(\d{4})-(\d{2})-(\d{2})", r'\1/\2/\3')
    Out[6]: '1991/02/28'
    

    相关文章

      网友评论

          本文标题:有用的python代码片段

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