超超高速Python入門

はじめに

筆者が独断と偏見で記載したPython初心者の方のために感覚を掴むためのざっくりとした1ページでまとめた超超高速Python入門。全ての内容を網羅するものではない。

少し詳細化したものは以下の「超高速Python入門」に記載している。

Udemyもお薦め。

Udemy – 【完全初心者向け】絶対に挫折させないPython入門講座

Udemy – 独学で身につけるPython〜基礎編〜【業務効率化・自動化で残業を無くそう!】

Udemy – みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習

入出力(print, input)

値を出力する

print関数でコンソール上に出力する。複数の場合は、カンマで区切れば出力可能。

x="Hello World"
y="Hello"
z="World"

print(x)
print(y,z)

## 出力
## Hello World
## Hello World

値を入力して変数へ格納する

以下のようにinput関数を使用する。入力時のメッセージを設定できる。

x = input("入力してください : ")
print(x) # 確認のため出力

上記を実行すると以下のように対話形式で入力を問われる。一つ目の123は入力された文字で、二つ目の123は出力された文字である。

$ python input.py 
入力してください : 123
123 

データ型・演算(int, float, str)

データ型

基本的には、str型(文字型)、int型(整数型)、float型(浮動小数点型)がある。str型(文字型)は、「”」「’」で囲む必要がある。

a = "Hello" # str型
b = 'Hello' # str型
c = Hello   ## エラー 

d = '2021'  # str型
e = 2021    # int型

f = '1.23'  # str型
g = 1.23    # float型

# 以下でデータ型を確認できる
print(type(変数))

文字列の演算

文字列の演算は結合した結果となる。

x = "Hello"
y = "World"

# 加算
print(x + y)

## 出力
## 'HelloWorld'

# 乗算
print(x * 3)

# 出力
# 'HelloHelloHello'

数値の演算

x = 1
y = 2.5

z1 = x + y
print(z1)
print(type(z1))
# 出力
# 3.5
# <class 'float'>

z2 = x - y
print(z2)
print(type(z2))
# 出力
# -1.5
# <class 'float'>

z3 = x * y
print(z3)
print(type(z3))
# 出力
# 2.5
# <class 'float'> 

z4 = x / y
print(z4)
print(type(z4))
# 出力
# 0.4
# <class 'float'>

z5 = x % y
print(z5)
print(type(z5))
# 出力
# 1.0
# <class 'float'>

z6 = x ** y
print(z6)
print(type(z6))
# 出力
# 1.0
# <class 'float'>

配列型(list, numpy)

配列のデータ型として、list型とNumpyライブラリがある。似ているところもあるが、違う点もある。

list型

初期化・定義(異なるデータ型でもOK)

## 一次元
list1 = [ 1 , "B" , 3.2 ]

## 二次元配列
list1 = [ [ 1.2 , "D" , 3 ] , [ 4 , 5.6 , "E" ] ]

要素指定

list2 = [ 1 , 2 , 3 , 4 , 5 , 6 ]

print(list2[2])
## 出力
## 3

print(list2[-1])
## 出力
## 6

print(list2[1:4])
## 出力
## [2, 3, 4]

追加

list3 = [ 1 , 2 , 3 ]

list3.append(4)
print(list3)
## 出力
## [1, 2, 3, 4]

その他

list4_1 = [ "A" , "B" , "C" ]
list4_2 = [ 1 , 2 , 3 ]

## 要素数取得
print(len(list4_1))
### 出力
### 3

## 結合
print(list4_1 + list4_2)
### 出力
### [ "A" , "B" , "C" , 1 , 2 , 3 ]

Numpy

import文

import numpy as np

初期化・定義(同じデータ型のみ)

list1 = [ 1 , "A" , 3 ]
np1 = np.array(list1)
print(np1)
print(np1.dtype) # .dtypeで要素のデータ型を確認できる

## 出力
## ['1' 'A' '3']
## <U21

## 0で初期化する場合
np_zero = np.zeros([ 2 , 3 ])
print(np_zero)

### 出力
### [[0. 0. 0.]
### [0. 0. 0.]]

要素指定

np2 = np.array([ 1 , 2 , 3 , 4 , 5 , 6 ])

print(np2[2])
## 出力
## 3

print(np2[-1])
## 出力
## 6

print(np2[1:4])
## 出力
## [2, 3, 4]

追加

np3_1 = np.array([ 1 , 2 , 3 ])
np3_2 = np.append(np3_1, [ 4 , 5 , 6 ])
print(np3_2)

## 出力
## [1, 2, 3, 4, 5, 6]

演算

np4_1 = np.array([ 1 , 2 , 3 ])
np4_2 = np.array([ 4 , 5 , 6 ])

print(np4_1 + np4_2)

## 出力
## [5, 7, 9]

print(np4_1 + 10)

## 出力
## [11, 12, 13]

リサイズ

np5_1 = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ])
np5_2 = np5_1.reshape( 5, 2 )
print(np5_2)

## 出力
## [[ 1  2]
## [ 3  4]
## [ 5  6]
## [ 7  8]
## [ 9 10]]

型変更

np6_1 = np.array([ 1 , 2 , 3 ])
np6_2 = np6_1.astype(np.float64)

print(np6_1)
print(np6_1.dtype)
print(np6_2)
print(np6_2.dtype)

# 出力
# [1 2 3]
# int64
# [1. 2. 3.]
# float64

その他

np7 = np.array([ [ 1 , 2 , 3 ],[ 4 , 5 , 6 ] ])

## 配列のサイズを取得(タプル型で取得)
print(np7.shape)

### 出力
### (2, 3)

## 配列を一次元に変更
np7_1d = np7.flatten()
print(np7_1d)

## 出力
## [1 2 3 4 5 6]

条件文(if, elif, else)

if-elif-else文の書き方は以下である。elif=else if である。

if x >= 90:
    print("Great")
elif  x >= 60:
    print("Better")
else :
    print("Bad")

ループ(for, while)

ループとしてはfor文とwhile文がある。特にfor文での配列の使い方は最初に知っておいた方が良い。

for文

for i in range(10):
    print(i)

## 出力
## 0
## 1
## 2
## ...
## 9
##10

x = ["apple", "lemon", "orange"]
for s in x:
    print(s)

## 出力
## apple
## lemon
## orange

while文

i = 0
while i < 3:
    print(i)
    i+=1

## 出力
## 0
## 1
## 2

関数(def)

関数の定義と呼び出しの書き方は以下に記載する。

# 関数定義
def niji_function(x, a, b=10):
    y = a * x + b
    return y

# 関数呼び出し
output =  niji_function(3, 2)
print(output)

## 出力
## 16

ファイル読み書き(open, numpy)

以下のtest.txtのようなデータがある場合のファイル読み書きを記載する。

apple
lemon
orange
import numpy as np

# 読み込み - open関数
with open('test.txt') as f:
    print(f.read())

## 出力
## apple
## lemon
## orange


# 読み込み - Numpy
data = np.loadtxt('test.txt', dtype='unicode')
print(data)

## 出力
## ['apple' 'lemon' 'orange']



# 書き込み - open関数
## 一つの値を書き込む
data = 'apple'
with open('test_write_str.txt', mode='w') as f:
    f.write(data)


## 一次元リストの値を書き込む
list_data = ['apple','lemon','orange']
with open('test_write_list.txt', mode='w') as f:
    for data in list_data:
        f.write(data)


# 書き込み - Numpy
## リストを書き込み
list_data = ['apple','lemon','orange']
np.savetxt('test_write_np_1.txt', list_data, fmt='%s')


## Numpyを書き込み
np_data = np.array(list_data)
np.savetxt('test_write_np_2.txt', np_data, fmt='%s') # 文字列の場合は、'%s'

ライブラリ紹介

  • Matplotlib
    • グラフを簡単に描画することができる。
  • Pandas
    • 2-D(二次元配列)に特化したライブラリである。表形式でデータを扱うことができ、SQLと同等の処理が可能。Numpyやlistとも互換性があり、Jupyter notebookとも相性が良い。
  • Scikit-learn
    • 機械学習を簡単に体験/使用できる。(簡単にできてしまうので、アルゴリズムの勉強には向いていない)
  • Flask
    • Webアプリ開発を簡単に体験できる。
  • Selenium
    • ブラウザ操作・スクレイピングが簡単にできる。

詳細は以下の記事に記載。

【超高速Python入門】ライブラリ紹介

おわりに

超超高速Python入門は以上。各項目を少し詳細化したものは以下にまとめて記載している。