• 13个提升码速的python小技巧


    小伙伴们,是不是每次在写python的时候都苦于只会写一些笨重的代码有时不得不借助万能的搜索引擎呢?我也是!话不多说,下面为大家带来一些提升码速的小技巧吧。

    1 交换值

    x, y = 1, 2
    print(x, y) # 1 2
    x, y = y, x
    print(x, y) # 2 1
    

    如上可以在同一个赋值符号下赋予多个值,并且他们是同时进行的,而传统的交换一般需要借助一个tmp,如下

    tmp=x
    x=y # y赋值给x之后x就改变了,所以需要事先存一个tmp
    t=tmp
    

    2 list转string

    sentence_list = ["my", "name", "is", "George"]
    sentence_string = " ".join(sentence_list)
    print(sentence_string) # my name is George
    

    3 string转list

    sentence_string = "my name is George"
    sentence_string.split()
    print(sentence_string)
    

    技巧2和3都是处理文件任务中的重要操作。

    4 初始化相同值的list

    [0]*100 # 包含100个0的list 
    [6.6]*45 # 包含45个6.6的list
    

    5 合并字典

    x = {'a': 1, 'b': 2}
    y = {'b': 3, 'c': 4}
    z = {**x, **y}
    

    6 翻转string

    name = "George"
    name[::-1]
    print(name[::-1]) # egroeG
    

    7 函数返回多个值

    def get_a_string():
        a = "George"
        b = "is"
        c = "cool"
        return a, b, c
    sentence = get_a_string()
    (a, b, c) = sentence
    

    8 列表解析(List comprehension)

    a = [1, 2, 3]
    b = [num*2 for num in a] 
    print(b) # [2, 4, 6]
    

    9 遍历字典

    m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 
    for key, value in m.items():
        print('{0}: {1}'.format(key, value))
    

    结果如下:

    a: 1
    b: 2
    c: 3
    d: 4
    

    10 遍历列表以及下标

    m = ['a', 'b', 'c', 'd']
    for index, value in enumerate(m):
        print('{0}: {1}'.format(index, value))
    

    11 删去无用的字符

    name = "  George "
    name_2 = "George///"
    name.strip() # 删去空格符 "George"
    name_2.strip("/") # 删去'/' "George"
    

    12 找到列表中的众数

    test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
    print(max(set(test), key = test.count)) # 4
    

    13 字典转XML

    from xml.etree.ElementTree import Element
    def dict_to_xml(tag, d):
        '''
        Turn a simple dict of key/value pairs into XML
        '''
        elem = Element(tag)
        for key, val in d.items():
            child = Element(key)
            child.text = str(val)
            elem.append(child)
        return elem
    

    这个会在做一些标注文件的时候用到。

    看到这个觉得有用的话不妨给个一键三连~>O<。

  • 相关阅读:
    TFS 2012使用简介(一)
    Android手机应用程序开发环境配置(Eclipse+Java+ADT)
    关于 all-delete-orphan
    Rest中的XML与JSON的序列化与反序列化
    C#Base64编码
    Visual Studio 2013支持Xamarin的解决方案
    【转】[WCF REST] 帮助页面与自动消息格式(JSON/XML)选择
    【转】 MEF 和 MAF
    Enable tfs feature in sharepoint
    Using a local farm account for a SharePoint 2013 installation
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13281633.html
Copyright © 2020-2023  润新知