Pythonコードで注意すべきことはいくつかあります


プログラミングの過程で、言語周辺の知識とテクニックを多く理解して、優秀なプログラマーになることを加速させることができます.
Pythonプログラマーにとって、本稿で述べたことに注意する必要があります.Zen of Python(Pythonの禅)を見てもいいです.この中にはいくつかの注意事項が言及されています.例を挙げると、急速に向上するのに役立ちます.
1.醜いよりきれい
1つの機能を実現します:1列のデータを読み出して、偶数だけを返して2で割ります.次のコード、どちらがいいですか?
halve_evens_only = lambda nums: map(lambda i: i/2, filter(lambda i: not i%2, nums))

 VS
 def halve_evens_only(nums):
    return [i/2 for i in nums if not i % 2] 

2.Pythonで簡単なことを覚えておく
#       
a, b = b, a

#   (slice)     step  。(      python     [start:stop:step], :[    :    :   ])
a = [1,2,3,4,5]
>>> a[::2]  #         2   
[1,3,5]

#      ,`x[::-1]`   x        
>>> a[::-1]
[5,4,3,2,1]

#      
>>> x[::-1]
[5, 4, 3, 2, 1]

>>> x[::-2]
[5, 3, 1] 

 
3.可変オブジェクトをデフォルトとして使用しない
def function(x, l=[]):          #    

def function(x, l=None):        #     
  if l is None:
l = []

これはdef宣言が実行されると、デフォルトパラメータが常に評価されるためです.
 
4.itemsではなくiteritemsを使用
iteritemsはgeneratorsを使用するので、非常に大きなリストで反復する場合、iteritemsのほうがいいです.
d = {1: "1", 2: "2", 3: "3"}
for key, val in d.items()       #            
for key, val in d.iteritems()   #         
 
 
5.typeではなくisinstanceを使用
#      

if type(s) == type(""): ...
if type(seq) == list or \
type(seq) == tuple: ...

#     

if isinstance(s, basestring): ...
if isinstance(seq, (list, tuple)): ...

理由:stackoverflow
 
strではなくbasestringを使用していることに注意してください.unicodeオブジェクトが文字列であれば、チェックしようとする可能性があります.例:
>>> a=u'aaaa'
>>> print isinstance(a, basestring)
True
>>> print isinstance(a, str)
False

これは、Python 3.0以降のバージョンでは、strとunicodeの2つの文字列タイプがあるためです.
 
6.各種容器について
Pythonには様々なコンテナデータ型があり、特定の場合、listやdictなどの内蔵コンテナよりも良い選択です.
ほとんどの人がそれを使わないと確信しています.私の周りの不注意な人は、次のようにコードを書くかもしれません.
freqs = {}
for c in "abracadabra":
    try:
        freqs[c] += 1
    except:
        freqs[c] = 1

次はより良い解決策だと言う人もいます.
freqs = {}
for c in "abracadabra":
    freqs[c] = freqs.get(c, 0) + 1

より正確にはcollectionタイプdefaultdictを使用する必要があります.
from collections import defaultdict
freqs = defaultdict(int)
for c in "abracadabra":
    freqs[c] += 1

その他のコンテナ:
namedtuple()    #     ,              
deque           #        ,            
Counter   # dict  ,        
OrderedDict   # dict  ,           
defaultdict   # dict  ,        ,       
  
7.Pythonでクラスを作成するマジックメソッド(magic methods)
__eq__(self, other)      #    ==       
__ne__(self, other)      #    !=       
__lt__(self, other)      #    <       
__gt__(self, other)      #    >       
__le__(self, other)      #    <=       
__ge__(self, other)      #    >=       
 
8.必要に応じてEllipsisを使用する(省略記号「...」)
Ellipsisは、高次元データ構造をスライスするために使用されます.スライス(:)として挿入し、すべての次元に多次元スライスを拡張します.例:
>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)

#   ,    4   2x2x2x2,    4          ,     ellipsis  。

>>> a[..., 0].flatten()
array([ 0,  2,  4,  6,  8, 10, 12, 14])

#     

>>> a[:,:,:,0].flatten()
array([ 0,  2,  4,  6,  8, 10, 12, 14])
 
原文:a few things to remember while coding in python