Pythonの高度なテクニック

5322 ワード

Pythonの高度なテクニック
Pythonの開発にはどのような高度なテクニックがありますか?これは前の問題を知っていて、私はいくつかのよくあるテクニックをまとめました.ここでは、あまり高級ではないかもしれませんが、これらをマスターすると、少なくともあなたのコードをPythonicのように見ることができます.もしあなたがまだクラスC言語のスタイルで書いているなら、code reviewではツッコミを入れられるかもしれません.
リスト導出式
>>> chars = [ c for c in 'python' ]
>>> chars
['p', 'y', 't', 'h', 'o', 'n']

ディクショナリガイド
>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> double_dict1 = {k:v*2 for (k,v) in dict1.items()}
>>> double_dict1
{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}

しゅうごうゆうどうしき
>>> set1 = {1,2,3,4}
>>> double_set = {i*2 for i in set1}
>>> double_set
{8, 2, 4, 6}

辞書のマージ
>>> x = {'a':1,'b':2}
>>> y = {'c':3, 'd':4}
>>> z = {**x, **y}
>>> z
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

リストのコピー
>>> nums = [1,2,3]
>>> nums[::]
[1, 2, 3]
>>> copy_nums = nums[::]
>>> copy_nums
[1, 2, 3]

リストの反転
>>> reverse_nums = nums[::-1]
>>> reverse_nums
[3, 2, 1]

変数交換
>>> a,b = 1, 2
>>> a ,b = b,a
>>> a
2
>>> b
1

高度な取り外し
>>> a, *b = 1,2,3
>>> a
1
>>> b
[2, 3]

または
>>> a, *b, c = 1,2,3,4,5
>>> a
1
>>> b
[2, 3, 4]
>>> c
5

関数は複数の値(実際には自動packingコンポーネントグループ)を返し、unpackingは4つの変数に値を割り当てます.
>>> def f():
...     return 1, 2, 3, 4
...
>>> a, b, c, d = f()
>>> a
1
>>> d
4

リストを文字列に結合
>>> " ".join(["I", "Love", "Python"])
'I Love Python'

チェーン比較
>>> if a > 2 and a < 5:
...     pass
...
>>> if 2

yield from
#      field from
def dup(n):
    for i in range(n):
        yield i
        yield i

#   yield from
def dup(n):
    for i in range(n):
    yield from [i, i]

for i in dup(3):
    print(i)

>>>
0
0
1
1
2
2

in代替or
>>> if x == 1 or x == 2 or x == 3:
...     pass
...
>>> if x in (1,2,3):
...     pass

複数のif elseに代わる辞書
def fun(x):
    if x == 'a':
        return 1
    elif x == 'b':
        return 2
    else:
        return None

def fun(x):
    return {"a": 1, "b": 2}.get(x)

下付き索引の列挙
>>> for i, e in enumerate(["a","b","c"]):
...     print(i, e)
...
0 a
1 b
2 c

ビルダー
注意リスト導出式を区別し、ジェネレータの効率を向上
>>> g = (i**2 for i in range(5))
>>> g
 at 0x10881e518>
>>> for i in g:
...     print(i)
...
0
1
4
9
16

注意リスト導出式を区別し、ジェネレータの効率を向上
>>> g = (i**2 for i in range(5))
>>> g
 at 0x10881e518>
>>> for i in g:
...     print(i)
...
0
1
4
9
16

デフォルトディクショナリdefaultdict
>>> d = dict()
>>> d['nums']
KeyError: 'nums'
>>>

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["nums"]
[]

文字列の書式設定
>>> lang = 'python'
>>> f'{lang} is most popular language in the world'
'python is most popular language in the world'

リストに最も多く表示される要素
>>> nums = [1,2,3,3]
>>> max(set(nums), key=nums.count)
3

  
from collections import Counter
>>> Counter(nums).most_common()[0][0]
3

ファイルの読み書き
>>> with open("test.txt", "w") as f:
...     f.writelines("hello")

オブジェクトタイプを判断し、複数のタイプを指定できます
>>> isinstance(a, (int, str))
True

文字列のstartswith,endswithも似ています
>>> "http://foofish.net".startswith(('http','https'))
True
>>> "https://foofish.net".startswith(('http','https'))
True

strとreprの違い
>>> str(datetime.now())
'2018-11-20 00:31:54.839605'
>>> repr(datetime.now())
'datetime.datetime(2018, 11, 20, 0, 32, 0, 579521)'

前者は人間に友好的で、可読性がより強く、後者はコンピュータに友好的で、obj==eval(repr(obj))をサポートする.
アクセサリーを使う
def makebold(f):
return lambda: "" + f() + ""

def makeitalic(f):
return lambda: "" + f() + ""

@makebold
@makeitalic
def say():
return "Hello"

>>> say()
Hello

デコレーションを使わないと、読みやすさが非常に悪い
def say():
return "Hello"

>>> makebold(makeitalic(say))()
Hello

テキストアドレス