LoginSignup
3
2

More than 3 years have passed since last update.

Python学習メモ

Last updated at Posted at 2020-01-19

はじめに

pythonの勉強の為、学習内容をメモしたものです。
誤記などあればご指摘ください。

組み込み関数


# 型変換
# intに変換
int("100")     # 10進数
int("100", 2)  # 2進数
int("100", 16) # 16進数
# float値に変換
float()
# 文字列に変換
str()
# 文字の出力
print("文字列")
print("文字列"+"文字列2")  # 文字列を連結する
print("文字列"+ str(100)) # 数値を文字に変えて連結 
print("文字列",100)       # 文字と数字連結(間にスペースが入る)
# 文字の入力
test = input()

# 合計
list = [1,2,3]
sum(list) # 結果 : 6

# 最大値
max(list) # 結果 : 3

# 最小値
min(list) # 結果 : 1

# 長さ
len(list) # 結果 : 3

for文

loop = [0,1,2,3]

# 配列数分ループする
for i in loop:
    # ループ内容

# 指定回数分ループ
for i in range(5):
    # ループ内容

# 特定の範囲でループさせる
for i in range(2,4):
    # ループ内容

while文

cnt = 1
while cnt <= 10:
   print(cnt)
   cnt = cnt + 1 # カウント加算

ループ制御

制御分 説明
break ループを抜ける(終了)
continue ループの最初に戻る
else ループの最後に実行する

else文の使い方

elseはループが終わった後に実行されます。
ただし、break文でループを抜けた場合、elseは実行されません。

Class=["田中","鈴木","佐藤"]
check ="田中"
# クラスの名前に「山田」がいるか確認
for name in Class:
   if check == name:
      print(name+"はクラスメイトです")
      break
else:
   print(check +"はクラスメイトではありません")

if文

testA = 1

if 1 == test:
    # True時の処理
else:
    # false時の処理

testB = "TEST"
if "T" in testB:
    # True時の処理
elif "B" in testB:
    # true時の処理


演算子

比較演算子

演算子  説明
A == B AとBが等しい
A != B AとBが異なる
A > B AはBより大きい
A < B AはBより小さい
A >= B AはB以上
A <= B AはB以下
A in B Aの要素がBに存在する

論理演算子

演算子 説明
A and B AかつB
A or B AまたはB

A < B and B < C
こような場合は、以下のような書き方も可能
A < B < C

ビット演算子

演算子 説明
A | B 論理和(OR)
A & B 論理積(AND)
A ^ B 排他的論理和(XOR)
A << B, A >> B シフト演算

関数

def Name1():
  # 関数処理
  return 0

# デフォルト引数を定義
def Name1():
  # 関数処理
  return 0

# デフォルト引数を定義
def Name2(name="名無し"):
 print( "あなたの名前は" + name + "です" )

# デフォルト引数を定義
def NameAndAge(name="名無し", age=25):
 print( "あなたの名前は" + name + "です" )
 print( "あなたの年齢は" , age,"才です" )


# キーワードを指定する
NameAndAge(age=12, name="太郎")

モジュール

import random                 # モジュールを読み込む
import random as rm           # モジュールに名前を指定する 
from statistics import median # モジュール内の関数を読み込む
from statistics import *      # モジュール内の全ての関数を読み込む

組み込みデータ型

数値型

型名 説明
int 整数型
float 浮動小数点型
complex 複素数型

XX進数表記

XX進数 表記 10進数から変換 XX進数から10進数に変換
16進数 0xffff hex(65535) int("0xffff",16)
2進数 0b1111 bin(15) int("0b1111",2)
8進数 0o777 oct(511) int("0c777",8)

文字列型

型名 説明
str 文字列型
bytes ファイルなどから読み込んだ文字列を扱う

置換 / 削除

test = "ABCDE"
test2 = test.replace("B","O")  # BをOに置換
test3 = test.replace("B","")   # Bを削除
# ただし、元の変数は変化しない
test   # "ABCDE"
test2  # "AOCDE"
test3  # "ACDE"

分割 / 連結

test = "1 2 3 4 5"

# スペースで分割する
test_split = test.split(" ")
#[.]でtest_splitのデータを連結する 
test_join = ".".join(test_split ) 

test          # "1 2 3 4 5"
test_split    # ["1","2","3","4","5"]
test_join     # "1.2.3.4.5"

その他のメソッド

メソッド 説明
str.find( 検索文字 [ ,開始 ,終了 ] ) 文字列を先頭から検索 , ヒットしないときは-1を返す
str.rfind( 検索文字 [ ,開始 ,終了 ] ) 文字列を末尾から検索 , ヒットしないときは-1を返す
str.index( 検索文字 [ ,開始 ,終了 ]) 文字列を先頭から検索 , ヒットしないときはValueErrorを返す
str.rindex( 検索文字 [ ,開始 ,終了 ]) 文字列を末尾から検索 , ヒットしないときはValueErrorを返す
str.startwith(検索文字 [ ,開始, 終了 ]) 検索文字開始しているときにTrueを返す
str.endwith( 検索文字 [ ,開始 ,終了 ]) 検索文字終了しているときにTrueを返す

フォーマット

formatを使用して文字列を差し込む

test= "私の名前は{}です"
test.format("太郎")                 # 私の名前は太郎です

#順番を指定する
test ="彼の名前は{0}です。{0}の年齢は{1}才です。"
test.format("次郎","25")            # 彼の名前は次郎です。次郎の年齢は25才です。

# キーワードを指定する
test ="彼の名前は{Name}です。{Name}の年齢は{Age}才です。"
test.format(Name="次郎",Age="25")   # 彼の名前は次郎です。次郎の年齢は25才です。

# ディクショナリで指定する
test = "{0[name]} は {0[age]}才です"
dictionary = {'name':'太郎' , 'age':'14'}
test.format(dictionary)            # 太郎 は 14才です

# 表記を指定する
test = "私の名前は{:>10}です"       # 右詰め
test.format("太郎")                # 私の名前は     太郎です

test = "{:.1%}"
test.format(0.25)                   # 25.0%

# f文字列で表示(python3.6以降)
name="太郎"
f"私の名前は{name}です"

エスケープ文字

文字 説明
\n 改行
\r 改行(CR)
\t 水平タブ
\f 改ページ
\' シングルクオーテーション
\" ダブルクォーテーション
\\ バックスラッシュ
\0 null

raw文字列

rをつけると、文字をそのまま表示する

raw = r"c:\Users\XX\Document"

bool型

TrueかFalseの値を取得

シーケンス

複数の要素を順番に並べた方をさす。
※ 文字列型(str型, bytes型)もシーケンスの仲間
ディクショナリ型とset型は順番という概念がない為、シーケンスには含まれない。

リスト

# リストの宣言
list = [1,2,3]
list2= [2,3,4]

# リストの連結
list3 = list + list2
list3 # 結果 : [1,2,3,2,3,4]

# 先頭を指定
list[0] = 0
list # 結果 : [0,2,3]

# 末尾を指定
list[-1] = 1
list # 結果 : [0,2,1]

# スライスの指定
slice = [0,1,2,3,4,5]
slice[1:3] # [1,2]
slice[:4]  # [0, 1, 2, 3]
slice[3:]  # [3, 4, 5]
# 偶数を指定
slice[::2] # [0,2,4] 
# スライスで置き換え
slice[1:2] = [10,11]
slice      # [0, 'a', 'b', 2, 3, 4, 5]
# スライスで削除
slice = [0,1,2,3,4,5]
del slice[4:]
slice      # [0, 1, 2, 3]

# 要素の削除
list = [0,1,2]
del list[2]
list # 結果 : [0,1]

# 要素の並び替え(昇順)
list = [3,5,2,1,0]
list.sort()
list    # [0, 1, 2, 3, 5]

# 要素の並び替え(降順)
list = [3,5,2,1,0]
list.sort(reverse=True)
list    # [5, 3, 2, 1, 0]

# 並び替えをカスタマイズ
# 配列の数字の合計が大きい順にソートする
def sumAll(num):
   # 配列の数字を合計して返す
   return num[0] + num[1] + num[2]

list = [[10, 50, 30],[20, 50, 40],[80, 60, 70]]
list.sort(key=sumAll, reverse=True)
list # [[80, 60, 70], [20, 50, 40], [10, 50, 30]]
メソッド名 説明
reverse() 逆順にする
remove() 取り除く
append() 末尾に要素を追加
expend() 末尾にシーケンスを追加
pop() 末尾を削除して、削除した値を返す
index() 検索したい要素を探し、インデックスを返す。見つからない場合はValueErrorを返す

タプル

タプルはリストによく似ているが、要素を変更出来ない。

# タプルの宣言
Months =("Jan","Feb","Mar","Apr","May","Jun","Jul")
# または
Months ="Jan","Feb","Mar","Apr","May","Jun","Jul"

# 1要素の時は最後にカンマを入れる
Day= ("Mon",)
# 連結はOK
Months = Months + ("Aug","Sep","Oct","Nov","Dec")

# アンパック代入
a = 1
b = 2
a , b = b , a
a     # 2
b     # 1

キーとして使用する

タプルは変更できないシーケンスの為、ディクショナリのキーや、
setの要素にすることが出来る

# 誕生日をディクショナリに登録
birthdays = {("4月","1日"):"山田太郎",
            ("6月","6日"):"山田花子",
            ("11月","11日"):"山田次郎"}
# 日付を指定
birthday =("6月","6日")
# for文で一致するキーを探す
for day in birthdays:
    if birthday == day:
        print(birthdays[day]) # 山田花子
        break

set

重複しない要素を管理する為に使うデータ


test1 = {1,2,3}
test2 = {3,4,5}

# 和集合
test1 | test2                # {1, 2, 3, 4, 5}
test1.union(test2)           # {1, 2, 3, 4, 5}

# 差集合
test1 - test2                # {1, 2}
test1.difference(test2)      # {1, 2}
# 論理積
test1 & test2                # {3}
test1.intersection(test2)    # {3}

# 排他的論理和
test1 ^ test2                     # {1, 2, 4, 5}
test1.symmetric_difference(test2) # {1, 2, 4, 5}

# リストからsetに変換
list = [1,2,3,4,5]
set(list)                    # {1, 2, 3, 4, 5}
# 比較
testA = {1,2,3,4,5,6}
testB = {3,4,5}
Check = testA & testB

if 4 in Check:
    print("4はTestAとTestBに含まれる")
if {3,4} <= Check:
    print("3,4はTestAとTestBに含まれる")



辞書(ディクショナリ)

KeyとValue(値)を紐づけて配列を管理する

# ディクショナリ型を定義
test = { "名前": "太郎",
         "年齢": "25"
         "出身": "東京"}

# dict()を使用して定義
dict([['key1','value1'],['key2','value2']])  # {'key1': 'value1', 'key2': 'value2'}
dict(key1='value1', key2='value2')           # {'key1': 'value1', 'key2': 'value2'}

# 追加する
test ={'名前':'太郎'}      # {'名前': '太郎'}
test["性別"] ="男"
test                       # {'名前': '太郎', '性別': '男'}

# updateメソッドで組み合わせる
test = {'名前': '太郎', '性別': '男'}
test.update({'性別':'女','年齢':'12歳'})
test # {'名前': '太郎', '性別': '女', '年齢': '12歳'}


# 削除する
test = {'名前': '太郎', '性別': '男'}
del test["性別"]
test                       # {'名前': '太郎'}

# 要素の有無を確認し要素を追加
test = {'名前':'五郎','年齢':'12'}
word = "年齢"
if word in test:
    # 存在する
   test[word] = test[word]+'才'
else:
    # 存在しない
    test[word] = '未記入'
test

# getを使って要素を追加
test = {'名前':'五郎'}
word = "年齢"

test[word] = test.get(word, '未記入')
test                   # {'名前': '五郎', '年齢': '未記入'}


変更 可 / 不可 データ

データ型 タイプ
リスト 変更可能(mutable)
ディクショナリ 変更可能(mutable)
set 変更可能(mutable)
bytearray 変更可能(mutable)
タプル 変更不可(immutable)
str/bytes 変更不可(immutable)

コメント

# コメントの先頭に#をつける

docstring

docstring(ドックストリング)を使用して関数の解説を追加する

def docstring():
    '''
    docstringテスト
     テスト1
     テスト2
     テスト3
    '''
    Test = "docstringを実行しました"
    print(Test)

print(docstring.__doc__)   # docstringの解説を文字列で取得
help(docstring)            # helpから関数の解説を確認
3
2
3

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
3
2