LoginSignup
18
17

More than 5 years have passed since last update.

Python Codeを優雅に

Last updated at Posted at 2019-02-16

時々,あなたはVery CoolなPythonコードを見たことがあるでしょうか.
その単純さ,その優雅さに驚いています.
あなたは感心するしか仕方がありません.
このように書くことができるのか!とビックルする
Pythonicのスキルを身につけることができれば,Coolなコードを書くことができます.

"_"について

これはよく使う機能けど,少数の人がしかしらない.
ターミナルでコードを書いて結果を得たとき,変数をつけ忘れることがあるでしょうか.
このとき,"_"を使って一番近い結果を得ることができます.

>>> 10 * 2
20
>>> _
20

文字結合

文字を結合するとき,習慣的に"+"を結合で使う人がいますが,
for文でメモリがどんどん減らされ,力つきるます.

string = ['p','y','t','h','o','n']

# Bad
def fun(string):
    all_string = ''
    for i in string:
        all_string += i
    return all_string

# Good
def fun(string):
    all_string = ''.join(string)
    return all_string

>>> "python"

強大なzip()

zip関数はいろんな場面で活用することができます.

例1:行列をchange

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Bad
re_a = [[row[col] for row in a] for col in range(len(a))]

# Good
re_a = list(zip(*a))

>>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

例2:dictのkeyとvalueをchange

a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Bad
def reverse_dict(a):
    new_dict = {}
    for k,v in a.items():
        new_dict[v] = k
    return new_dict

# Good
def reverse_dict(a):
    k = a.keys()
    v = a.values()
    new_dict = dict(zip(v, k))
    return new_dict

>>> {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

変数の中身をChange

大学1年のC言語の授業が思い出す.

# Bad
tmp = a
a = b
b = tmp

# Good
a, b = b, a

リストの要素とインデックスを取得

a = [8, 23, 45, 12, 78]
for index, value in enumerate(a):
    print(index , value)

0 8
1 23
2 45
3 12
4 78

1行で例外を得る

try:
    pass
except (ExceptionA,ExceptionB,.....) as e:
    pass

リストを同じ大きさのブロックに分ける

a = [1, 2, 3, 4, 5, 6]
list(zip( *[iter(a)]*2 ))

>>> [(1, 2), (3, 4), (5, 6)]

文字列を反転

a = 'Love Python'

#Bad
list_a = list(a)
list_a.reverse()
re_a = ''.join(list_a) 

#Good
re_a = a[::-1]

>>> 'nohtyP evoL'

メモリとさらば

crash = dict(zip(range(10 **0xA), range(10 **0xA))) 

今回の「Python Codeを優雅にChange」は以上で終わります.
読んでいただいてありがとうございます.

18
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17