LoginSignup
0
0

Python備忘録1(変数)

Last updated at Posted at 2023-06-29

数値

乗算

multiplication.py
print(2 * 3)
print(2 ** 3)
console
6
8
記号 意味
* 乗算
** 累乗

除算

division.py
value = 25

print(value / 4)
# 25/4 = 6余り1
print(value // 4)
print(value % 4)
console
6.25
6
1
記号 意味
/ 除算(小数表示)
// 除算(余りは切り捨て)
% 剰余

インクリメント・デクリメント

increment-decrement.py
value = 10
value += 3  # value = value + 3
print(value)

value = 10
value -= 3 # value = value - 3
print(value)
console
13
7
記号 意味
+= 右辺の値を足す
-= 右辺の値を引く

シフト演算

shift.py
"""
8(10) = 1000(2) 
1000 を右へ1移動
0100(2) = 4(10)
"""
value = 8   
print(value >> 1)

"""
8(10) = 1000(2) 
  1000(2) を左へ1移動 
1 0000(2) = 16(10)
"""
value = 8
print(value << 1)
console
4
16
記号 意味
>> 右シフト
<< 左シフト

ビット演算

bit.py
"""
AND
1100(2) = 12(10)
0110(2) =  6(10)
 
0100(2) = 4(10)
"""
print(12 & 6)

"""
OR
1100(2) = 12(10)
0110(2) =  6(10)

1110(2) = 14(10)
"""
print(12 | 6)

"""
XOR
1100(2) = 12(10)
0110(2) =  6(10)

1010(2) = 10(10)
"""
print(12 ^ 6)
console
4
14
10
記号 意味
& AND(ビット単位論理積)
| OR(ビット単位論理和)
^ XOR(ビット単位排他的論理和)

N進数

base.py
"""
2進数
先頭に0bをつけると2進数となる
bin()で10進数を2進数に変換する
"""

num = 0b10001 # 17
print(num)

print(bin(20)) # 0b10100


"""
8進数
先頭に0oをつけると8進数となる
oct()で10進数を8進数に変換する
"""
num = 0o21 # 17
print(num)

print(oct(20)) # 0o24


"""
16進数
先頭に0xをつけると16進数となる
oct()で10進数を16進数に変換する
"""
num = 0x11 # 17
print(num)

print(hex(20)) # 0x14
console
17
0b10100
17
0o24
17
0x14
意味
0b 2進数
0o 8進数
0x 16進数
意味
bin() 10進数を2進数に変換する
oct() 10進数を8進数に変換する
hex() 10進数を16進数に変換する

複素数

complex.py
# 複素数
"""
虚数部は数値+jとする
"""    
a = 1 + 2j
b = 5 + 3j

print(a,b)


print(a+b)
print(a-b)
print(a*b)


print("---")

"""
complex(実数,虚数)
"""    
a = complex(1,2)
b = complex(5,3)
print(a,b)

print(a+b)
print(a-b)
print(a*b)

print("---")

"""
realは実数部を取り出す
imagは虚数部を取り出す
"""    
print(a.real)
print(a.imag)
console
(1+2j) (5+3j)
(6+5j)
(-4-1j)
(-1+13j)
---
(1+2j) (5+3j)
(6+5j)
(-4-1j)
(-1+13j)
---
1.0
2.0
意味
j 虚数部
意味
complex(a,b) a=実数,b=虚数
意味
num.real 実数部を取り出す
num.imag 虚数部を取り出す

文字列

format

format.py
name = 'towamz'
age = 18


# format文
print('name = {},age = {}'.format(name,age))

print(f'name = {name},age = {age}')  # 3.6以降

print(f'{name = },{age = }') # 3.8以降

console
name = towamz,age = 18
name = towamz,age = 18
name = 'towamz',age = 18

format(詳細1)

format-detail1.py
name = 'towamz'
print(f'名前は{name:10}です')
print(f'名前は{name:>10}です')
print(f'名前は{name:^10}です')
print(f'名前は{name:<10}です')
print(f'名前は{name:-^10}です')
console
名前はtowamz    です
名前は    towamzです
名前は  towamz  です
名前はtowamz    です
名前は--towamz--です

format(詳細2)

format-detail2.py
age = 20
# 3桁分のスペース(ない場合は空白)
print(f'年齢は{age:3d}です')
# 3桁分のスペース(ない場合は0)
print(f'年齢は{age:03d}です')
# 3桁分のスペース(ない場合は指定文字でパディング)
print(f'年齢は{age:*>3d}です')
console
年齢は 20です
年齢は020です
年齢は*20です

format(詳細3)

format-detail3.py
weight = 90.1
print(f'体重は{weight:6.2f}です')

num1 = 12345.6789
# 3桁区切り・有効桁同時指定
print(f"{num1:,.2f}")
# ゼロパディング・3桁区切り・有効桁同時指定
print(f"{num1:012,.2f}")
console
体重は 90.10です
12,345.68
0,012,345.68

input

input.py
name = input('あなたの名前は何ですか?')

print(name) 
console
あなたの名前は何ですか?towamz
towamz

代入

string.py
name1 = "towamz"
name2 = 'joe'
name3 = """towamz
joe"""

print(name1)
print(type(name1))

print(name2)
print(type(name2))

print(name3)
print(type(name3))
console
towamz
<class 'str'>
joe
<class 'str'>
towamz
joe
<class 'str'>
演算子 意味
"" 文字列(単行)
'' 文字列(単行)
"""""" 文字列(複数行)

結合

concatenation.py
name1 = "towamz"
name2 = 'joe'

print(name1 * 10)
print(name1 + name2)

console
towamztowamztowamztowamztowamztowamztowamztowamztowamztowamz
towamzjoe
演算子 意味
* 文字列を指定回数分結合する
+ 文字列と文字列を結合する

slice

slice.py
str1 = 'abcdef'

print(str1[0])
print(str1[1])

print(str1[-1])
print(str1[-2])
console
a
b
f
e
  • str[]
引数 意味
正数 文字列の先頭から指定の文字を取り出す(先頭は0)
負数 文字列の末尾から指定の文字を取り出す(末尾は-1)

slice2

slice2.py
msg = 'abcdefghijklmnopqrstuvwxyz'

print(msg[:5])
print(msg[5:15])
print(msg[15:])

print(msg[::2])
print(msg[::3])
console
abcde
fghijklmno
pqrstuvwxyz
acegikmoqsuwy
adgjmpsvy
  • str[num1:num2:num3]
引数 意味
num1 切り取る先頭のインデックス番号を指定
(省略=先頭から)
num2 切り取る末尾の(インデックス番号-1)を指定
(省略=末尾まで)
num3 (数)文字ごと切り取る
(省略=1文字ずつ)

strip

strip.py
msg = " abc "

print(msg + '-')
print(msg.strip() + '-')
print(msg.lstrip() + '-')
print(msg.rstrip() + '-')


msg = "aaaaaabcdeabccbaedcbaaaaaa"

print(msg)
print(msg.strip('a'))
print(msg.lstrip('a'))
print(msg.rstrip('a'))


msg = "abcdeabccbaedcba"

print(msg)
print(msg.strip('abc'))
print(msg.lstrip('abc'))
print(msg.rstrip('abc'))

print(msg.strip('cba'))
print(msg.lstrip('cba'))
print(msg.rstrip('cba'))

print(msg.strip('ace'))
print(msg.lstrip('ace'))
print(msg.rstrip('ace'))
console
 abc -
abc-
abc -
 abc-

aaaaaabcdeabccbaedcbaaaaaa
bcdeabccbaedcb
bcdeabccbaedcbaaaaaa
aaaaaabcdeabccbaedcb

abcdeabccbaedcba
deabccbaed
deabccbaedcba
abcdeabccbaed
deabccbaed
deabccbaedcba
abcdeabccbaed
bcdeabccbaedcb
bcdeabccbaedcba
abcdeabccbaedcb

"""
# 見やすいように空白を挿入
# 'abc'
abcdeabccbaedcba
   deabccbaed
   deabccbaedcba
abcdeabccbaed

# 'cba'
abcdeabccbaedcba
   deabccbaed
   deabccbaedcba
abcdeabccbaed

# 'ace'
abcdeabccbaedcba
 bcdeabccbaedcb
 bcdeabccbaedcba
abcdeabccbaedcb
"""
メソッド 意味
str.strip() 指定した文字列を左右から削除する
str.lstrip() 指定した文字列を左から削除する
str.rstrip() 指定した文字列を右から削除する
  • 引数に指定した文字列がなくなったらそこで削除を終了する
  • 引数を指定しないと空白を削除する

case

case.py
msg = 'abcABCabcABCabcABCabcABC'

print(msg)
print(msg.upper())
print(msg.lower())
print(msg.swapcase())
print(msg.capitalize())
console
abcABCabcABCabcABCabcABC
ABCABCABCABCABCABCABCABC
abcabcabcabcabcabcabcabc
ABCabcABCabcABCabcABCabc
Abcabcabcabcabcabcabcabc
メソッド 意味
str.upper() すべて大文字に置き換える
str.lower() すべて小文字に置き換える
str.swapcase() 小文字を大文字に、大文字を小文字に置き換える
str.capitalize() 先頭1文字を大文字に、2文字以降を小文字に置き換える

replace

replace.py
msg = 'abcABCabcABCabcABCabcABC'

print(msg.replace('ABC','FFF'))
print(msg.replace('ABC','FFF',1))
print(msg.replace('ABC','FFF',3))
console
abcFFFabcFFFabcFFFabcFFF
abcFFFabcABCabcABCabcABC
abcFFFabcFFFabcFFFabcABC
  • str.replace(str1,str2,num)
引数 意味
str1 置換前の文字列
str2 置換後の文字列
num 先頭からnum回まで置き換える。
(省略=すべて置き換える)

count

count.py
msg = "abcdeabcbc"

print(msg.count('abcde'))
print(msg.count('abc'))
print(msg.count('bc'))
print(msg.count('xyz'))
console
1
2
3
0
メソッド 意味
str.count() 指定した文字列の回数を表示する

find/index

find-index.py
msg = 'ABCDEABC'

print(msg.find('ABC'))
print(msg.rfind('ABC'))


print(msg.index('ABC'))
print(msg.rindex('ABC'))

print(msg.find('Z'))
print(msg.index('Z'))
console
0
5
0
5
-1
Traceback (most recent call last):
  File "find-index.py", line 7, in <module>
    print(msg.index('Z'))
ValueError: substring not found
メソッド 意味
str.find 指定した文字列が最初に出現する位置のインデックス番号
str.rfind 指定した文字列が末尾から最初に出現する位置のインデックス番号
str.index 指定した文字列が最初に出現する位置のインデックス番号
str.rindex 指定した文字列が末尾から最初に出現する位置のインデックス番号
  • 文字列が見つからない時の動作
メソッド 動作
find/rfind -1
index/rindex 例外が発生する

エンコード・デコード

encodedecode.py
name1 = "towamz"

byte_name1 = name1.encode('utf-8')
print(byte_name1)
print(type(byte_name1))

str_name1 = byte_name1.decode('utf-8')
print(str_name1)
print(type(str_name1))
console
b'towamz'
<class 'bytes'>
towamz
<class 'str'>
メソッド 意味
encode 文字列型からバイト型に変換する
decode バイト型から文字列型に変換する

判定

startswith/endswith

startwiths-endswith.py
msg = "abcdeabcxyzvwxyz"

print(msg.startswith('ab'))
print(msg.startswith('yz'))

print(msg.endswith('ab'))
print(msg.endswith('yz'))
console
True
False
False
True
メソッド 意味
str.startswith() 指定した文字列で開始しているか判定する
str.endswith() 指定した文字列で終了しているか判定する

islower/isupper

islower-isupper.py
msg = 'towamz'
print(msg.islower())

msg = 'toWamz'
print(msg.islower())

msg = 'toWamz'
print(msg.isupper())

msg = 'TOWAMZ'
print(msg.isupper())
console
True
False
False
True
メソッド 意味
str.islower() 文字列がすべて小文字か判定
str.isupper() 文字列がすべて大文字か判定

数値・文字列変換

conversion.py
# 数値から文字列へ変換
i_num = 10
f_num = 10.5

i_str = str(i_num)
f_str = str(f_num)

print(i_num,type(i_num))
print(f_num,type(f_num))
print(i_str,type(i_str))
print(f_str,type(f_str))


# 文字列から数値へ変換
i_str2 = '100'
f_str2 = '100.5'

i_num2 = int(i_str2)
f_num2 = float(f_str2)

print(i_str2,type(i_str2))
print(f_str2,type(f_str2))
print(i_num2,type(i_num2))
print(f_num2,type(f_num2))
console
10 <class 'int'>
10.5 <class 'float'>
10 <class 'str'>
10.5 <class 'str'>
100 <class 'str'>
100.5 <class 'str'>
100 <class 'int'>
100.5 <class 'float'>
関数 意味
str() 数値(整数型・浮動小数点数型)を文字列に変換する
int() 文字列を整数型に変換する
float() 文字列を浮動小数点数型に変換する

list

インデックス指定1

list-index1.py
list1 = ['abc','def','ghi','jkl']
# 引数なしで空のリストを作成できる
list2 = []

print(list1)
# 正数で先頭からのインデックス番号の値を取得できる
print(list1[0])
# 負数で末尾からのインデックス番号の値を取得できる
print(list1[-1])

# 数値や文字列が混在していてもいい。また一部のみ2次元にすることも可能
list3 = ['abc',['uvw','xyz',1],102,'jkl']

print(list3[1][2])
print(list3)

# リストは値を書き換えることができる
list3[1][2] = 'towamz'
print(list3)
console
['abc', 'def', 'ghi', 'jkl']
abc
jkl
1
['abc', ['uvw', 'xyz', 1], 102, 'jkl']
['abc', ['uvw', 'xyz', 'towamz'], 102, 'jkl']
  • list[num1][num2][num3]・・・・
引数 意味
正数 リストの先頭から指定のインデックスの値を取り出す(先頭は0)
負数 リストの末尾から指定のインデックスの値を取り出す(末尾は-1)
  • 2次元以上も可能

インデックス指定2

list-index2.py
list1 = ['abc','def','ghi','jkl','mno','pqr','stu','vwx']

list2 = list1[:4]
list3 = list1[4:]
list4 = list1[1:6:2]

print(list1)
print(list2)
print(list3)
print(list4)

console
['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
['abc', 'def', 'ghi', 'jkl']
['mno', 'pqr', 'stu', 'vwx']
['def', 'jkl', 'pqr']
  • list[num1:num2:num3]
引数 意味
num1 開始インデックス番号
num2 終了インデックス番号
num3 (数)要素ごとに取り出す

初期化

1次元

list-initialize-oneDimension.py
i = 3
val = 0
list1 = [val] * i

print(list1)
console
[0, 0, 0]

1次元2

list-initialize-oneDimension2.py
i = 3
val = 0

list1 = [val for _ in range(i)]
print(list1)
console
[0, 0, 0]

2次元

list-initialize-twoDimensions.py
# i*j の2次元配列を値valで生成
i = 3
j = 5
val = True
list1 = []

for _ in range(i):
    list1.append([val] * j)

print(list1)
console
[[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]]

2次元2

list-initialize-twoDimensions2.py
i = 3
j = 5
val = True

list1 = [[val for _ in range(j)] for _ in range(i)]
print(list1)
console
[[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]]

参照コピー・値コピー

list-refval.py
list1 = ['abc','def','ghi']

# 値コピー
list2 = list1[:]
list3 = list1.copy()
# 参照コピー
list4 = list1

# リストの末尾に結合する
list1.extend(['jkl','mno','pqr','stu','vwx'])

print("list1->",list1)
# list2はインデックスをつけて値コピーしているので、list1の値が変更されてもlist2は変わらない
print("list2->",list2)
# list3はcopyメソッドで値コピーしているので、list1の値が変更されてもlist3は変わらない
print("list3->",list3)
# list4は=で参照コピーしているので、list1の値が変更されるとlist4も変わる
print("list4->",list4)
console
list1-> ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
list2-> ['abc', 'def', 'ghi']
list3-> ['abc', 'def', 'ghi']
list4-> ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
メソッド 意味
list = list.copy() リストを値コピーする
list = list[:] リストを値コピーする
list = list リストを参照コピーする

append

list-append.py
list1 = ['abc','def','ghi']
print(list1)

# listの末尾に追加する
list1.append('jkl')
print(list1)

# リストを指定すると多次元になる
list1.append(['mno','pqr','stu','vwx'])
print(list1)
console
['abc', 'def', 'ghi']
['abc', 'def', 'ghi', 'jkl']
['abc', 'def', 'ghi', 'jkl', ['mno', 'pqr', 'stu', 'vwx']]
メソッド 意味
list.append(var) リストの末尾にデータを追加する(リストの場合は多次元になる)

extend

list-extend.py
list1 = ['abc','def','ghi']
print(list1)

# リストの末尾に結合する(多次元にならない)
list1.extend(['jkl','mno','pqr','stu','vwx'])
print(list1)
console
['abc', 'def', 'ghi']
['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
メソッド 意味
list.extend(var) リストの末尾にデータを追加する(リストの場合は結合されインデックスが増える)

insert

list-insert.py
list1 = ['abc','def','ghi','mno','pqr','stu','vwx']
print(list1)

list1.insert(3,'jkl')
print(list1)
console
['abc', 'def', 'ghi', 'mno', 'pqr', 'stu', 'vwx']
['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
メソッド 意味
list.insert(index,var) 指定のインデックス番号にデータを挿入する

pop

list-pop.py
list1 = ['a','b','c','d','e']
print(list1)

# 指定した要素を切り取りその値を返す
popVal = list1.pop(1)
print(list1)
print(popVal)

# 要素指定がない場合、末尾の要素を1つ切り取りその値を返す
popVal = list1.pop()
print(list1)
print(popVal)
console
['a', 'b', 'c', 'd', 'e']
['a', 'c', 'd', 'e']
b
['a', 'c', 'd']
e
メソッド 意味
list.pop(index) (index)要素を切り取りその値を返す
list.pop() 末尾の要素を1つ切り取りその値を返す

remove

list-remove.py
list1 = ['a','b','c','d','e','a','b','c','d','a','b','c','a','b','a']
print(list1)

# 先頭から最初の要素を1つ削除する
list1.remove('c')
print(list1)
console
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'a', 'b', 'a']
['a', 'b', 'd', 'e', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'a', 'b', 'a']
メソッド 意味
list.remove(var) 先頭から最初の指定の値と一致している要素を1つ削除する

count

list-count.py
list1 = ['a','b','c','d','e','a','b','c','d','a','b','c','a','b','a']

# 指定の値と一致している要素数を返す
print(list1.count('a'))
# 存在しない要素の場合0が返る
print(list1.count('z'))
console
5
0
メソッド 意味
list.count(var) 指定の値と一致している要素数を返す

index

list-index.py
list1 = ['a','b','c','d','e','a','b','c','d','a','b','c','a','b','a']

# 指定の値と一致している最初の要素のインデックス番号を返す
print(list1.index('c'))
# 存在しない要素の場合、例外が発生する
print(list1.index('z'))
console
2
Traceback (most recent call last):
  File "list-index.py", line 6, in <module>
    print(list1.index('z'))
ValueError: 'z' is not in list
メソッド 意味
list.index(var) 指定の値と一致している最初の要素のインデックス番号を返す

指定の値と一致しているインデックス番号をすべて取得

list-enumerate(index-all).py
list1 = ['a','b','c','d','e','a','b','c','d','a','b','c','a','b','a']

# 値がaのインデックス番号を取得
list2 = [i for i, x in enumerate(list1) if x == 'a']
print(list2)
console
[0, 5, 9, 12, 14]

sorted

list-sorted.py
list1 = ['rabbit','cat','elephant','tiger']
list2 = sorted(list1, key=len)
list3 = sorted(list1, key=len, reverse=True)

print(f'{list1}')
print(f'{list2}')
print(f'{list3}')


list4 = [1,3,-2,-5,10,8,-15]
list5 = sorted(list4, key=abs)
print(f'{list4}')
print(f'{list5}')


list12 = [3,2,7] # 平均値 4
list13 = [4,6,9] # 平均値 6.3
list14 = [2,10,5] # 平均値 5.6

list10 = [list12,list13,list14]
list11 = sorted(list10,key=lambda v: sum(v) / len(v),reverse=True)
print(list11[0])
console
['rabbit', 'cat', 'elephant', 'tiger']
['cat', 'tiger', 'rabbit', 'elephant']
['elephant', 'rabbit', 'tiger', 'cat']
[1, 3, -2, -5, 10, 8, -15]
[1, -2, 3, -5, 8, 10, -15]
[4, 6, 9]

clear

list-append.py
list1 = ['abc','def','ghi','jkl','mno','pqr','stu','vwx']
print(list1)

list1.clear()
print(list1)
console
['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
[]
メソッド 意味
list.clear() リストの要素をすべて削除する

list・数値,文字列変換

リスト(要素が文字列)から1行の文字列に変換

list-join.py
list1 = ['a','b','c','d','e']
s = ' '.join(list1)
print(s)  
console
a b c d e

リスト(要素が数値)から1行の文字列に変換

list-join2.py
list2 = [1,2,3,4,5]
print(' '.join(map(str, list2)))

print(' '.join(list2))
console
1 2 3 4 5
Traceback (most recent call last):
  File "list-join2.py", line 4, in <module>
    print(' '.join(list2))
TypeError: sequence item 0: expected str instance, int found
  • 要素が数値の場合、joinが使えないのでそれぞれの要素をstr関数で文字列に変換した後結合する

2次元listを1次元listへ変換

list-2dTo1d.py
import itertools

list1 = []
for _ in range(3):
    list1.append([0] * 4)
print(list1)

# itertools
list2 = list(itertools.chain.from_iterable(list1))
print(f'list2->{list2}')

# リスト内包表記
list3 = [x for row in list1 for x in row]
print(f'list3->{list3}')
console
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
list2->[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
list3->[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

dictionary

インデックス指定

dictionary-index.py
city = {'name':'Tokyo','capital':'Shinjuku','population':13988129,'region':'Kansai','area':2194000}
print(city)

# キーを指定してその値を変えることができる
city['region'] = 'Kanto'
print(city)

# キーを指定して値を取る
print(city['name'])
# 存在しないKeyを指定すると例外が発生
print(city['nonreg'])
console
{'name': 'Tokyo', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kansai', 'area': 2194000}
{'name': 'Tokyo', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kanto', 'area': 2194000}
Tokyo
Traceback (most recent call last):
  File "dictionary-index.py", line 11, in <module>
    print(city['nonreg'])
KeyError: 'nonreg'

get

dictionary-get.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kanto','area':2194000}

# キーを指定して値を取る
print(city.get('name'))

# 存在しないKeyを指定すると第2引数に指定した値を返す。指定がない場合はnoneを返す
print(city.get('nokey'))
print(city.get('nokey','textWhenNoExist'))
print(city.get('nokey',1))
console
Tokyo
None
textWhenNoExist
1
メソッド 意味

keys/values/items

dictionary-keys-values-items.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kanto','area':2194000}

print(city.keys())
print(city.values())
print(city.items())

# dictionaryからKeyを取り出す
for key in city.keys():
    print(f'{key = }')

# dictionaryから値を取り出す
for value in city.values():
    print(f'{value = }')

# dictionaryからKeyと値をセットで取り出す
for key,value in city.items():
    print(f'{key = }, {value = }')
console
dict_keys(['name', 'prefType', 'capital', 'population', 'region', 'area'])
dict_values(['Tokyo', '都', 'Shinjuku', 13988129, 'Kanto', 2194000])
dict_items([('name', 'Tokyo'), ('prefType', '都'), ('capital', 'Shinjuku'), ('population', 13988129), ('region', 'Kanto'), ('area', 2194000)])
key = 'name'
key = 'prefType'
key = 'capital'
key = 'population'
key = 'region'
key = 'area'
value = 'Tokyo'
value = '都'
value = 'Shinjuku'
value = 13988129
value = 'Kanto'
value = 2194000
key = 'name', value = 'Tokyo'
key = 'prefType', value = '都'
key = 'capital', value = 'Shinjuku'
key = 'population', value = 13988129
key = 'region', value = 'Kanto'
key = 'area', value = 2194000
メソッド 意味

update

dictionary-update.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129}
city_additional = {'region':'Kanto','area':2194000}
print(city)

# dictionaryを末尾に別のdictionaryを結合する
city.update(city_additional)
print(city)
console
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129}
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kanto', 'area': 2194000}
メソッド 意味

pop

dictionary-pop.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kanto','area':2194000}
print(city)

# 指定したキーを削除して、その値を返す
value = city.pop('population')
print(city)
print(value)
console
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kanto', 'area': 2194000}
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'region': 'Kanto', 'area': 2194000}
13988129
メソッド 意味

popitem

dictionary-popitem.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kanto','area':2194000}
print(city)

# 末尾のキーを削除して、キーと値をタプルを返す
value = city.popitem()
print(city)
print(value)
console
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kanto', 'area': 2194000}
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kanto'}
('area', 2194000)
メソッド 意味

clear

dictionary-clear.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kanto','area':2194000}
print(city)

# dictionary要素をすべて駆除して空にする
city.clear()
print(city)
console
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kanto', 'area': 2194000}
{}
メソッド 意味

del

dictionary-del.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kansai','area':2194000,1:100}
print(city)

# 指定したキーを削除する
del city['prefType']
# キーは整数型でも可能
del city[1]
print(city)

# キーを指定しないと変数自体を削除
del city
print(city)
console
{'name': 'Tokyo', 'prefType': '都', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kansai', 'area': 2194000, 1: 100}
{'name': 'Tokyo', 'capital': 'Shinjuku', 'population': 13988129, 'region': 'Kansai', 'area': 2194000}
Traceback (most recent call last):
  File "dictionary-del.py", line 12, in <module>
    print(city)
NameError: name 'city' is not defined
メソッド 意味

if

dictionary-if.py
city = {'name':'Tokyo','prefType':'','capital':'Shinjuku','population':13988129,'region':'Kanto','area':2194000}

# Keyが存在する場合ifを実行する
if 'prefType' in city:
    print('{}の{}庁所在地は{}です。'.format(city['name'],city['prefType'],city['capital']))
else:
    print('{}の県庁所在地は{}です。'.format(city['name'],city['capital']))


# 'prefType'キーを削除
del city['prefType']

# Keyが存在しない場合elseを実行する
if 'prefType' in city:
    print('{}の{}庁所在地は{}です。'.format(city['name'],city['prefType'],city['capital']))
else:
    print('{}の県庁所在地は{}です。'.format(city['name'],city['capital']))
console
Tokyoの都庁所在地はShinjukuです。
Tokyoの県庁所在地はShinjukuです。
メソッド 意味

tuple

インデックス指定

tuple-index.py
eastAsia = ('Japan','China','Korea')
southeastAsia = ('Singapore','Malaysia','Thailand','Vietnam')

print(eastAsia[0])
print(eastAsia)
print(type(eastAsia))

# タプルに新しい値を追加してタプルを上書きできる。
# タプルが要素が1つの場合は、,をつける必要がある
southeastAsia = southeastAsia + ('Indonesia',)
# タプルが要素が2つ以上の場合は、,をつける必要はない
southeastAsia = southeastAsia + ('Laos','Cambodia')
print(southeastAsia)

Asia = eastAsia + southeastAsia 
print(Asia)

# タプルをインデックスを指定して一部を書き換えることはできない
eastAsia[0] = 'newCountry'
console
Japan
('Japan', 'China', 'Korea')
<class 'tuple'>
('Singapore', 'Malaysia', 'Thailand', 'Vietnam', 'Indonesia', 'Laos', 'Cambodia')
('Japan', 'China', 'Korea', 'Singapore', 'Malaysia', 'Thailand', 'Vietnam', 'Indonesia', 'Laos', 'Cambodia')
Traceback (most recent call last):
  File "tuple-index", line 21, in <module>
    eastAsia[0] = 'newCountry'
TypeError: 'tuple' object does not support item assignment

count

tuple-count.py
tuple1 = ('a','b','c','d','e','a','b','c','d','a','b','c','a','b','a')

print(tuple1.count('b'))
console
4
メソッド 意味
tuple.count(var) 指定の値と一致している要素数を返す

index

tuple-index.py
tuple1 = ('a','b','c','d','e','a','b','c','d','a','b','c','a','b','a')

print(tuple1.index('b'))
console
1
メソッド 意味
tuple.index(var) 指定の値と一致している最初の要素のインデックス番号を返す

list・tuple変換

conversion-list-tuple.py
list_eastAsia = ['Japan','China','Korea']
print(list_eastAsia)
print(type(list_eastAsia))

# tuple関数でlistからtupleに変換できる
tuple_eastAsia = tuple(list_eastAsia)
print(tuple_eastAsia)
print(type(tuple_eastAsia))

# list関数でtupleからlistに変換できる
list_eastAsia2 = list(tuple_eastAsia)
print(list_eastAsia2)
print(type(list_eastAsia2))
console
['Japan', 'China', 'Korea']
<class 'list'>
('Japan', 'China', 'Korea')
<class 'tuple'>
['Japan', 'China', 'Korea']
<class 'list'>
関数 意味
tuple listからtupleに変換
list tupleからlistに変換

set

in/not in(インデックス指定不可)

set-in-notin.py
set1 = {'a','b','c','d','a','b'}

# 同じ値は1つにまとめられる
# 順不同である(実行するたびに順番が異なる)
print(set1)

# in/not inで値が存在するか確認できる
print('a' in set1)
print('e' in set1)
print('a' not in set1)
print('e' not in set1)

# setはインデックス指定することができない
print(set1[1])
console
{'d', 'b', 'a', 'c'}
True
False
False
True
Traceback (most recent call last):
  File "set-in-notin.py", line 14, in <module>
    print(set1[1])
TypeError: 'set' object is not subscriptable
メソッド 意味

add

set-add.py
set1 = {'a','b','c','d','a','b'}
print(set1)

# addで値を追加できる
set1.add('e')
print(set1)
console
{'b', 'c', 'd', 'a'}
{'d', 'c', 'b', 'a', 'e'}
メソッド 意味

remove

set-remove.py
set1 = {'a','b','c','d'}
print(set1)

# removeで指定した値を削除できる
set1.remove('a')
print(set1)

# 存在しない値を指定すると例外が発生する
set1.remove('a')
console
{'b', 'a', 'd', 'c'}
{'b', 'd', 'c'}
Traceback (most recent call last):
  File "/home/towam/python-design-pattern-master/basic/28_29-3.py", line 8, in <module>
    set1.remove('a')
KeyError: 'a'
メソッド 意味

discard

set-discard.py
set1 = {'a','b','c','d'}
print(set1)

# discardで指定した値を削除できる
set1.discard('a')
print(set1)

# 存在しない値を指定しても何も起こらない
set1.discard('a')
print(set1)
console
{'c', 'b', 'd', 'a'}
{'c', 'b', 'd'}
{'c', 'b', 'd'}
メソッド 意味

pop

set-pop.py
set1 = {'a','b','c','d'}
print(set1)

# popで任意の1つの要素を取り出し値を返す(実行するたびに変える値は変わる)
val = set1.pop()
print(val, set1)
console
{'c', 'd', 'b', 'a'}
c {'d', 'b', 'a'}
メソッド 意味

clear

set-clear.py
set1 = {'a','b','c','d'}
print(set1)

# clearですべての要素を削除する
set1.clear()
print(set1)
console
{'a', 'b', 'd', 'c'}
set()
メソッド 意味

集合演算

union

setoperation-union.py
set1 = {'a','b','c','d'}
set2 = {'c','d','e','f'}

# union(和集合)
set3 = set1 | set2
set4 = set1.union(set2)
print(set3)
print(set4)
console
{'f', 'c', 'a', 'e', 'b', 'd'}
{'f', 'c', 'a', 'e', 'b', 'd'}
メソッド 意味

intersection

setoperation-intersection.py
set1 = {'a','b','c','d'}
set2 = {'c','d','e','f'}

# intersection(積集合)
set3 = set1 & set2
set4 = set1.intersection(set2)
print(set3)
print(set4)
console
{'d', 'c'}
{'d', 'c'}
メソッド 意味

difference

setoperation-difference.py
set1 = {'a','b','c','d'}
set2 = {'c','d','e','f'}

# difference(差集合)
set3 = set1 - set2
set4 = set1.difference(set2)
print(set3)
print(set4)
console
{'a', 'b'}
{'a', 'b'}
メソッド 意味

symmentric_difference

setoperation-.py
set1 = {'a','b','c','d'}
set2 = {'c','d','e','f'}

# symmentric_difference(対象差)
set3 = set1 ^ set2
set4 = set1.symmetric_difference(set2)
print(set3)
print(set4)
console
{'b', 'f', 'a', 'e'}
{'b', 'f', 'a', 'e'}
メソッド 意味

判定

issubset

setoperation-issubset.py
set1 = {'a','b'}
set2 = {'a','b','c','d'}

# issubset(部分集合)
print(set1.issubset(set2))
print(set2.issubset(set1))
console
True
False
メソッド 意味

issuperset

setoperation-issuperset.py
set1 = {'a','b'}
set2 = {'a','b','c','d'}

# issuperset(上位集合)
print(set1.issuperset(set2))
print(set2.issuperset(set1))
console
False
True
メソッド 意味

isdisjoint

setoperation-isdisjoint.py
set1 = {'a','b'}
set2 = {'a','b','c','d'}
set3 = {'e'}

# isdisjoint(互いに素、同じ要素が1つもない)
print(set1.isdisjoint(set2))
print(set1.isdisjoint(set3))
console
False
True
メソッド 意味

内包表記

内包表記

comprehension.py
# list
list1 = [i for i in range(10)] 
print(type(list1),list1)

# dictionary
dict1 = {str(i): i for i in range(10)}
print(type(dict1),dict1)

# tuple
tuple1 = tuple(i for i in range(10))
print(type(tuple1),tuple1)

# セット
set1 = {i for i in range(10)}
print(type(set1),set1)


# ジェネレーター
gen1 = (i for i in range(10))
print(type(gen1),gen1)

for i in range(5):
    print(next(gen1))
console
<class 'list'> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'dict'> {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
<class 'tuple'> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
<class 'set'> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
<class 'generator'> <generator object <genexpr> at 0x7fde078422d0>
0
1
2
3
4
メソッド 意味

内包表記2

comprehension2.py
listBase1 = [i for i in range(10)] 
listBase2 = [i for i in range(50)] 
dictBase1 = {
    'c':'cat',
    'd':'dog',
    'r':'rabbit'
}

print(type(listBase1),listBase1)
print(type(listBase2),listBase2)
print(type(dictBase1),dictBase1)


list1 = [i for i in listBase1] 
print(list1)

list2 = [i * 2 for i in listBase1] 
print(list2)

list3 = [i for i in listBase2 if any((i % 5 == 0, i % 3 == 0))]
print(list3)

# dictionaryのキーでリストを作る
list4 = [k for k in dictBase1.keys()]
# dictionaryの値でリストを作る
list5 = [dictBase1.get(k) for k in dictBase1.keys()]
print(list4)
print(list5)
console
<class 'list'> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'list'> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
<class 'dict'> {'c': 'cat', 'd': 'dog', 'r': 'rabbit'}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48]
['c', 'd', 'r']
['cat', 'dog', 'rabbit']
  • ほかのlistなどをもとに新しいlistなどを作ることができる
  • 条件式を付けることができる

内包表記3

comprehension3.py
def isPrimeNumber(num):
    if num < 2:
        return False

    numHalf = num // 2
    numHalf += 1

    for i in range(2,numHalf):
        if num % i == 0:
            return False
    return True

list1 = [i for i in range(100) if isPrimeNumber(i)]
list2 = [i for i in range(100) if isPrimeNumber(i) == False]
print(list1)
print(list2)
console
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]
  • 条件式に関数(戻り値がbool型)を使うことができる

内包表記4

comprehension4.py
list1 = ['#','.','#']
list2 = [1 if val == '#' else 0 for val in list1]

print(list2)
console
[1, 0, 1]
  • リストの値に基づいて、ほかの値のリストを作成できる
0
0
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
0
0