LoginSignup
1
7

More than 3 years have passed since last update.

Pythonの便利メソッドなど

Last updated at Posted at 2019-11-09

はじめに

Pythonは広く普及しており、開発者は多い。
一番の特徴はシンプルさだと思います。
例えば、hello worldを出力するのはただ一行でできるのです。ほかの言語ではなかなかできません。

image.png

出典:https://www.benfrederickson.com/ranking-programming-languages-by-github-users/

hello worldを出力

print("hello world!")

計算の便利さ

print(2 * 3)  //掛け算
print(2 ** 3) //べき乗

print(22 / 7) //小数あり
print(22 // 7) //整数

6
8
3.142857142857143
3

変数値交換

Go言語と同じく、temp変数不要で直接交換できます。

a = 10
b = 20
a, b = b, a
print(a)
print(b)

フィボナッチ数列を求める例:

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()

fib(900)

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

文字で連結できるjoinメソッド

color = ["red", "green", "blue"]
print(" ".join(color))

red green blue

指定文字列で配列のデータを簡単に連結できます。LOOPも不要で便利です。

文字列の反転

k8s = "kubernates"
print(k8s[::-1])

setanrebuk

メソッドを呼ぶ必要もありません。

配列の反転

文字列の反転よりは、配列の反転に使う場面が多いでしょう。

alphas = ["a", "b", "c", "d"]
print(alphas[::-1])

['d', 'c', 'b', 'a']

文字列反転の場合と同じ書き方です。

配列の重複値の排除

numbers = [4, 3, 2, 1, 1, 2, 3, 4]
print(list(set(numbers)))

[1, 2, 3, 4]

範囲比較

JAVAでは 6歳以上、18歳以下を判断したい場合、if (6 <= age && age <= 18) {}のように二つの計算式が必要です。
範囲判断はできません。Pythonなら、できます。

age = 10
if (6 <= age <= 18) :
    print("学生です。")

学生です。

一目でロジックがわかるので、便利ですね。

for else

elseはifと一緒に使うと思うでしょうが、Pythonなら、forと一緒に使うこともできます。

for i in range(5):
    print(i)
else:
    print("LOOP完了")

0
1
2
3
4
LOOP完了

ちょっと違和感があるかもしれません、Pythonならではの構文です。
これだけでは使い道はあまりないように見えますが、breakと一緒に使う場面で有用性が発揮されます。
breakでloopが中止される場合に、elseの処理は実行されません。

for i in range(5):
    if i > 3:
        break

    print(i)
else:
    print("LOOP完了")

0
1
2
3

辞書のgetでデフォルト値設定可能

user = {"lastName": "田中"}
print(user.get("firstName", "〇〇"))

〇〇

このような場合に,わざわざ値を取得した後、存在するかどうかの判断をする必要はないので便利です。

辞書のキーでソート

辞書のキーでソートする処理もよくあります。

user = {"userName": "田中", 
    "address3": "3",  
    "address2": "2", 
    "address1": "1" }
print(user)

print(sorted(user.items(), key = lambda x: x[1]))

{'userName': '田中', 'address3': '3', 'address2': '2', 'address1': '1'}
[('address1', '1'), ('address2', '2'), ('address3', '3'), ('userName', '田中')]

sortedメソッドを使って辞書のキーでソートした配列が生成されます。
これを使う場面は少なくはないでしょう。

enumerate関数

fruits = ['バナナ', 'リンゴ', 'みかん']
print(list(enumerate(fruits)))

[(0, 'バナナ'), (1, 'リンゴ'), (2, 'みかん')]
番号を付けることができます。

簡単に数種類の操作をまとめました。

Pythonではほかにもいろいろな便利メソッド、モジュールがあります。

以上

1
7
0

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
1
7