Pythonコード技術

21524 ワード

記事の目次
  • 、インタラクティブ割り当て
  • 、分割リスト
  • 、`in`判断文を使用する
  • 4、‘ジョイン’を使用して文字列を結合する
  • .
  • 、巡回リストおよびインデックス
  • 、導出式
  • 、循環ネスト
  • 、ジェネレータ代替リスト
  • 9、any/all関数を使用する
  • 10、属性
  • 11、with処理ファイルを使って
  • を開く.
  • 、withロックを使う
  • 13、Counterを使用した統計回数
  • Pythonの最大の利点の一つは文法が簡潔で、良いコードは疑似コードのように、清潔で、清潔で、一目瞭然です.Pythonic(優雅で、正真正銘で、きれいな)コードを書くには、大牛たちの書いたコードを多く見て学ぶ必要があります.
    1、相互割当
    a = 1
    b = 2
    temp = a
    a = b
    b = temp
    
    #   
    a, b = b, a
    
    2、分割リスト
    my_list = ['A', 'B', 'C']
    simple0 = simple_list[0]
    simple1 = simple_list[1]
    simple2 = simple_list[2]
    
    #   
    simpleA, simpleB, simpleC = my_list
    
    3、判断文をinを使用する
    if result == 'ok' or result == 1:
        '''    '''
    
    #    
    if result in ['ok', 1]:
        '''    '''
    
    4、joinを使って文字列を結合する
    colors = ['red', 'yellow', 'blue', 'green']
    result = ''
    for i in colors:
        result += i
    
    #   
    colors = ['red', 'yellow', 'blue', 'green']
    result = ''.join(colors)
    #                   
    
    5、リストと索引を巡回します.
    my_itmes = ['a', 'b', 'c', 'd', 'e']
    i = 0
    for item in my_itmes:
        print(i, item)
        i += 1
        
    #   
    my_itmes = ['a', 'b', 'c', 'd', 'e']
    for i, item in enumerate(my_itmes):
        print(i, item)
    
    6、導出式
    #      
    old_list = ['A', 'B', 'C', 'D', 'E']
    new_list = [item for item in old_list]
    
    #      
    dict = {'key1': 'value1', 'key2': 'value2'}
    d = {k: v for k, v in dict.items()}
    
    #      
    simple_set = {x ** 2 for x in [1, -1, 2]}
    
    7、循環ネスト
    x_list = ['a', 'b', 'c', 'd']
    y_list = ['A', 'B', 'C', 'D']
    z_list = ['1', '2', '3', '4']
    
    for x in x_list:
        for y in y_list:
            for z in z_list:
                print(x, y, z)
                
    #   
    from itertools import product
    
    for x, y, z in product(x_list, y_list, z_list):
        print(x, y, z)
    
    8、ジェネレータ代替リスト
    def calculate(n):
        return n ** 2
    
    
    def my_range(n):
        i = 0
        result = []
        while i < n:
            result.append(calculate(i))
            i += 1
        return result
    
    #   
    def my_range(n):
        i = 0
        while i < n:
            yield calculate(i)
            i += 1
    #              
    
    9、any/all関数を使う
    found = False
    for item in my_list:
        if condition(item):
            found = True
            break
    if found:
        '''    '''
    
    ##  
    if any(condition(item) for item in my_list):
    	 '''    '''
        
    # any   , all   
    
    10、属性
    class Clock(object):
        def __init__(self):
            self.__hour = 1
    
        def __setHour(self, hour):
            self.__hour = hour
    
        def __getHour(self):
            return self.__hour
    
        hour = property(__getHour, __setHour)
    
    11、with処理ファイルで開く
    f = open('text.txt')
    content = f.read()
    f.close()
    
    #   
    with open('text.txt') as f:
        content = f.read()
    
    12、withロックを使う
    import threading
    
    lock = threading.Lock()
    lock.acquire()
    try:
        '''    '''
    finally:
        lock.release()
    
    #   
    import threading
    lock = threading.Lock()
    
    with lock:
        '''    '''
    
    13、Counterを使用した統計回数
    my_list = ['a', 'a', 'b', 'c', 'c', 'c']
    
    def compute(my_list):
        #     
        my_dict = {}
    
        for key in my_list:
            if key not in my_dict:
                #            ,      1
                my_dict[key] = 1
            else:
                #           ,    1
                my_dict[key] = my_dict[key] + 1
        return my_dict
    
    #   
    from collections import Counter
    
    def compute(my_list):
        #     
        counter = Counter(my_list)
        return dict(counter)