まぬねこの足跡。。。

備忘録+たのしさ+ひっそりと

Python 集合(set)

概要

  • 重複も順序もない要素のあつまり
  • 順序がないため、インデックス指定での要素取得はできない。

集合 生成

「{}」、set()

空集合はset()のみ

set1= {2, 3, 2, 3, 1, 3, 1, 3, 3, 1}
print(set1)
print(type(set1))
# リストから
set2= set(['卯月', '皐月', '卯月', '水無月','卯月'])
print(set2)
print(type(set2))
# 空集合から
set3=set()
print(set3)
print(type(set3))
# タプルから
set4=set(('卯月', '皐月', '卯月', '水無月','卯月'))
print(set4)
print(type(set4))
# 辞書から
set5=set({'卯月': '4月', '皐月': '5月', '水無月': '6月'})
print(set5)
print(type(set5))

表示イメージ

{1, 2, 3}
<class 'set'>
{'卯月', '皐月', '水無月'}
<class 'set'>
set()
<class 'set'>
{'卯月', '皐月', '水無月'}
<class 'set'>
{'卯月', '皐月', '水無月'}
<class 'set'>

セット 組み込み関数

  • len(set)・・・要素数
  • x,y,z = set・・・ 多重代入
  • 判定
    • 値 in set・・・集合に含むか
    • 値 not in set・・・集合に含まないか

セット 集合演算

  • 和集合「|」
  • 積集合「&」
  • 差集合「-」
  • 対称差「^」

※メソッドもある。後述記載

# 和集合
print({1, 2, 3, 4} | {3, 4, 5, 6})
# 積集合
print({1, 2, 3, 4} & {3, 4, 5, 6})
# 差集合
print({1, 2, 3, 4} - {3, 4, 5, 6}) 
# 対称差
print({1, 2, 3, 4} ^ {3, 4, 5, 6})

表示イメージ

{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}

セット 比較合演算

  • 同一か判定「値==set」
  • 相違か判定「値!=set」
  • 包括関係
    • 値を全部含むか判定「値<=set」
    • 値を全部含み、集合の方が要素が多いか判定「値<set」]
print({1, 2, 3} <= {1, 2, 3})
print({1, 2} <= {2, 3, 4})
print({2, 3} <= {2, 3, 4})
print()
print({1, 2, 3} < {1, 2, 3})
print({1, 2, 3, 4} < {1, 2, 3})
print({1, 2, 3} < {1, 2, 3, 4})
print({1, 2} < {1, 2, 3})

表示イメージ

{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}

セット メソッド

add・・・要素の追加 ※破壊的

set.add(要素)

set1 = {1, 2, 3}
set1.add(10)
set1

表示イメージ

{1, 2, 3, 10}

add・・・要素の追加 ※破壊的

set.add(要素)

set1 = {1, 2, 3}
set1.add(10)
set1

表示イメージ

{1, 2, 3, 10}

add・・・要素の追加 ※破壊的

set.add(要素)

set1 = {1, 2, 3}
set1.add(10)
set1

表示イメージ

{1, 2, 3, 10}

remove・・・要素の削除 ※破壊的

set.remove(要素)

※削除対象が集合にないとエラー

set1 = {1, 22, 3}
set1.remove(22)
print(set1)
set1.remove(99)

表示イメージ

 {1, 3}
 ----------------------------------------------------------------
 KeyError      Traceback (most recent call last)

discard・・・要素の削除 ※破壊的

set.discard(要素)

※削除対象が集合になくても、エラーにならない。

set1 = {1, 22, 3}
set1.discard(22)
print(set1)
set1.discard(99)

表示イメージ

{1, 3}

clear・・・全要素の削除、空にする ※破壊的

set.clear()

set1 = {1, 2, 3}
set1.clear()
set1

表示イメージ

set()

pop・・・ランダムな要素の1つ取得 ※破壊的

set.pop()

空集合のとき、エラーになる。

set1 = {1, 2, 3}
print(set1.pop())
print(set1)

表示イメージ

1
{2, 3}

集合演算

  • union(set) 和集合
  • intersection(set) 積集合
  • difference(set) 差集合
  • symmetric_difference(set) 対称差
# 和集合
print({1, 2, 3, 4}.union({3, 4, 5, 6}))
# 積集合
print({1, 2, 3, 4}.intersection({3, 4, 5, 6}))
# 差集合
print({1, 2, 3, 4}.difference({3, 4, 5, 6}))
# 対称差
print({1, 2, 3, 4}.symmetric_difference({3, 4, 5, 6}))
表示イメージ
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}

Python 関数、引数、ラムダ式

概要

入力により処理を行い何か結果を返すプログラムの部品。何度も呼び出せる。
pythonでは、関数でさえ変数。

検証

def hensu():
    print("おいしいごはん")

type(hensu)

表示イメージ

function

関数定義

基本

def 関数名(引数1, 引数2....)
 処理
 return 戻り値

2行目以降、必ずインデントを入れる。
※プログラムの区分けをみわけている為。

def show(show):
    print(show)

def show2():
    print("オレンジ")

呼出し

show("みかん")
show2()

表示イメージ

オレンジ
みかん

戻り値 return

値を返してほしい時指定。
注意:戻り値にNoneを返す関数「print()など」を指定しても何もおこらない。

def plus(x, y):
  return x+y

呼出し

plus(2, 3)

表示イメージ

5

デフォルト引数

引数にデフォルト値を設定しておける。

def 関数名(引数1, 引数2=デフォルト値....)
 処理
 return 戻り値

※デフォルトを設定した引数以降は、全部引数を設定すること。
→引数2に設定したら、引数3以降も設定。

def plus(x, y=5, z=3):
    return x+y+z

呼出し

print(plus(2, 7, 4)) # 2+7+4
print(plus(2, 7)) # 2+7+3
print(plus(2)) #2+5+3

表示イメージ

8

キーワード引数

キーワード引数で関数呼出しができる。

関数名(引数1,キーワード引数=デフォルト値....)
 処理
 return 戻り値

def plus(x, y=5, zkey=3):
    return x+y+zkey

呼出し

print(plus(2, zkey=10)) # 2+5+10

表示イメージ

17

可変長引数

基本

引数前に「*」をつける。

*引数名

def hensu(*args):
    print(args)

hensu('ごはん', 'ライス', '飯')
表示イメージ
('ごはん', 'ライス', '飯')

リスト、タプル 可変長引数

def hensu(*args):
    print(args)
    
lis=['ごはん', 'ライス', '飯']
hensu(*lis)
tap=('ごはん', 'ライス', '飯')
hensu(*tap)
表示イメージ
('ごはん', 'ライス', '飯')
('ごはん', 'ライス', '飯')

辞書型 可変長引数

引数前に「**」をつける。

**辞書型引数名

def hensu(**args):
    print(args)
    
hensu(apr='卯月' , may= '皐月', june='水無月')
dic_strg ={'卯月': '4月', '皐月': '5月', '水無月': '6月'}
hensu(**dic_strg)
表示イメージ
{'apr': '卯月', 'may': '皐月', 'june': '水無月'}
{'卯月': '4月', '皐月': '5月', '水無月': '6月'}


引数のパラメータ

既存の関数を確認するときのルール。

def 関数名(  位置1, ,位置2,(前に/*がない)  /, 位置orキーワード,(前に/がある)  *, キーワード1 (前に*がある) ):

def関数名(引数1, ... , *args(引数の最後 キーワード引数専用) ):

引数 アンパック

引数リスト アンパック

リスト変数名に「*」をつける

print(list(range(3, 6)))

lis = [3, 6]
print(list(range(*lis))) # リストアンパック

表示イメージ

[3, 4, 5]
[3, 4, 5]

引数辞書 アンパック

リスト変数名に「**」をつける
辞書のキーワード=キーワード引数名にすること。

def moon(mm1, moon='10月', nextmoon='11月'):
    print("今月", mm1, end=' ')
    print("翌月", moon, end=' ')
    print("翌々月", nextmoon)

dic ={'mm1': '4月', 'moon': '5月', 'nextmoon': '6月'}
moon("わからない")
moon(dic)
moon(*dic)
moon(**dic)

表示イメージ

今月 わからない 翌月 10月 翌々月 11月
今月 {'mm1': '4月', 'moon': '5月', 'nextmoon': '6月'} 翌月 10月 翌々月 11月
今月 mm1 翌月 moon 翌々月 nextmoon
今月 4月 翌月 5月 翌々月 6月

ラムダ式 無名関数生成

無名の小さい関数。

書き方

変数= lambda 引数1, ... : 処理

引数に値を渡す時。

変数= (lambda 引数1, ... : 処理)(渡す値1,...)

oyatu = "みかん"
(lambda oyatu:oyatu+"おいしい!")(oyatu) 

num = list(map(lambda x:x**2,range(10))) #「lambda x:x**2」が無名関数
print(num)

表示イメージ

みかんおいしい!
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Python タプル(tuple)

概要

  • ()で囲む 省略もOK。
  • 複数のデータを要素としてまとめて取り扱うデータ
  • 構成要素:あらゆる型で混合してよい。
  • 他言語の配列に近い。
  • インデックスで要素を取得のみ。書換不可。

‐ シーケンス型

実行結果

word_tap=(1,2,3,4,5)
word_tap1=11,22,33,44,55
print(word_tap)
print(word_tap1)
print(word_tap[3])
print(word_tap[1:3])
print(type(word_tap))
kara_tap=() # 空のタプル
tap_1=(999,) # データ1つの時
print(kara_tap)
print(tap_1)

表示イメージ

(1, 2, 3, 4, 5)
(11, 22, 33, 44, 55)
4
(2, 3)
<class 'tuple'>
()
(999,)

変換

タプル→リスト 変換

word_tap=(1,2,3,4,5)
print(word_tap)
print(type(word_tap))
word_lis = list(word_tap)
print(word_lis)
print(type(word_lis))
表示イメージ
(1, 2, 3, 4, 5)
<class 'tuple'>
[1, 2, 3, 4, 5]
<class 'list'>

リスト→タプル 変換

word_lis=[1,2,3,4,5]
print(word_lis)
print(type(word_lis))
word_tap = tuple(word_lis)
print(word_tap)
print(type(word_tap))
表示イメージ
[1, 2, 3, 4, 5]
<class 'list'>
(1, 2, 3, 4, 5)
<class 'tuple'>

Python リスト(list)

概要

  • []で囲む
  • 複数のデータを要素としてまとめて取り扱うデータ
  • 構成要素:あらゆる型で混合してよい。
  • 他言語の配列に近い。
  • インデックスで要素を読書きできる。

‐ シーケンス型

money=1000
kaban=['財布','携帯',100]
bag = [10,'りんご', kaban,money]

print(bag)
print(type(bag))#データ型確認
bag[1]='みかん'
print(bag)

表示イメージ

[10, 'りんご', ['財布', '携帯', 100], 1000]
<class 'list'>
[10, 'みかん', ['財布', '携帯', 100], 1000]

インデックス

  • 0から始まる。基本, 左側に格納したデータから数える。
  • データの書換えが可能
  • 負のインデックス:後ろから数える。「-1」から始まる。
word=['a', 'b', 'c', 'd','e']
print(word[1])
print(word[-2])
word[1]='Z'
print(word)
word[3]='ZZZZ'
print(word)
print(type(word))#データ型確認

表示イメージ

b
d
['a', 'Z', 'c', 'd', 'e']
['a', 'Z', 'c', 'ZZZZ', 'e']
<class 'list'>

スライス

部分文字列を取得可能

文字変数名[ (開始) : (終了+1) ]

文字変数名[ (開始) : (終了+1) : 2(増分値) ]

  開始:省略時、0になる。
  終了+1:省略時、最大インデックスになる。
  増分値:省略時、1

word=['a', 'b', 'c', 'd','e','f','g','h','i','j','k']
print(word[1:4])
print(word[1:8:2])
print(word[:4])
print(word[5:])
word[1:4]='Z'
print(word)
word[1:4]='ZZZZZ'
print(word)
print(type(word))#データ型確認

表示イメージ

['b', 'c', 'd']
['b', 'd', 'f', 'h']
['a', 'b', 'c', 'd']
['f', 'g', 'h', 'i', 'j', 'k']
['a', 'Z', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
['a', 'Z', 'Z', 'Z', 'Z', 'Z', 'g', 'h', 'i', 'j', 'k']
<class 'list'>

多重リスト

リスト内にリスト。

nums_strgs = [[1, 2, 3], [10, 20, 30], ['a', 'b', 'c']]
print(nums_strgs)
print(nums_strgs[1])
print(nums_strgs[1][2])
nums_strgs[1][2]='AAA'
print(nums_strgs)
nums_strgs[1]=[11,22]
print(nums_strgs)

表示イメージ

[[1, 2, 3], [10, 20, 30], ['a', 'b', 'c']]
[10, 20, 30]
30
[[1, 2, 3], [10, 20, 'AAA'], ['a', 'b', 'c']]
[[1, 2, 3], [11, 22], ['a', 'b', 'c']]

リスト→新リスト 内包表記

シーケンスや iterableの要素に条件で絞ったり、要素を加工して新たなリストを生成。

基本

[ 要素加工 for 要素 in iterable ]

[x**2 for x in range(10)]

表示イメージ

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

複数のリストから要素を取得

[ 要素A,B...加工 for 要素A in iterableA for 要素B in iterableB ...]

[(x, y) for x in [1,2,3] for y in [3,1,4]]

表示イメージ

[(1, 3), (1, 1), (1, 4), (2, 3), (2, 1), (2, 4), (3, 3), (3, 1), (3, 4)]

条件で絞る

[ True要素の加工 for 要素 in iterable if 要素条件]

nums = [1,2,None,3,4,5]
[num for num in nums if num != None]

表示イメージ

[1, 2, 3, 4, 5]

入れ子(ネスト)・・・多次元リストを生成

[ [ 要素A,B...加工 for 要素A in iterableA ] (1次元(行)) for 要素B in iterableB ]
                              (2次元(列))

nums = [1,2,None,3,4,5]
rows = ['a', 'b', 'c', 'd', 'e']
[[row+str(col) for row in rows] for col in range(4)]

表示イメージ

[['a0', 'b0', 'c0', 'd0', 'e0'],
 ['a1', 'b1', 'c1', 'd1', 'e1'],
 ['a2', 'b2', 'c2', 'd2', 'e2'],
 ['a3', 'b3', 'c3', 'd3', 'e3']]

リスト→セット(集合) 内包表記

シーケンスや iterableの要素に条件で絞ったり、要素を加工して新たなセット(集合)を生成。

基本

{ 要素加工 for 要素 in iterable }

nums = [1,2,None,3,4,5]
sets={num for num in nums if num != None}
print(sets)

表示イメージ

{1, 2, 3, 4, 5}

リスト→辞書 内包表記

シーケンスや iterableの要素に条件で絞ったり、要素を加工して新たな辞書型を生成。

基本

{ 要素加工 for 要素 in iterable }

animals = ['cat', None,'dog', 'bird', 'horse']
animals_dic={animal:len(animal) for animal in animals if animal != None}
print(animals_dic)

表示イメージ

{'cat': 3, 'dog': 3, 'bird': 4, 'horse': 5}


演算子

演算子「+」

リストの連結

word=[1,2,3,4,5]
print(word+['a', 'b', 'c', 'd','e'])

表示イメージ

[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e']

演算子「*」

パターンA

word=[1,2,3,4,5]
print(word*3)
表示イメージ
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

パターンA

words= [[0, 1], [2, 3]]
lis = words*5
print(lis)
words[0][0] = 'AA' #参照渡しなので「*5」分、全部変わる
print(lis)
表示イメージ
[[0, 1], [2, 3], [0, 1], [2, 3], [0, 1], [2, 3], [0, 1], [2, 3], [0, 1], [2, 3]]
[['AA', 1], [2, 3], ['AA', 1], [2, 3], ['AA', 1], [2, 3], ['AA', 1], [2, 3], ['AA', 1], [2, 3]]

演算子「in」

word=[1,2,3,4,5]
print(1 in [1,2,3])
print(1 in word)
print(5 in [1,2,3])
print(5 in word)

表示イメージ

True
True
False
True

演算子「not in」

word=[1,2,3,4,5]
print(1 not in [1,2,3])
print(1 not in word)
print(5 not in [1,2,3])
print(5 not in word)

表示イメージ

False
False
True
False

関数・メソッド

素数 len関数

len(list)

word=[1,2,3,4,5]
print(len(word))

表示イメージ

5

最大値 max関数

max(list)

word=[1,2,3,4,5]
print(max(word))

表示イメージ

5

最小値 min関数

min(list)

word=[1,2,3,4,5]
print(min(word))

表示イメージ

1

総和 sum関数

sum(list)

word=[1,2,3,4,5]
print(sum(word))

表示イメージ

15

インデックス番号 indexメソッド

list.index(要素)

word=['a', 'b', 'c', 'd','e']
print(word.index('c'))

表示イメージ

2

並べ替え

ちょこっとメモ

破壊的

元のデータを変える。

非破壊的

元のデータは、変えない。

sort メソッド (破壊的)

sort(*, key=None, reverse=False)

reverse:Trueで降順

word=['z', 'c', 'f', '2','d','1']
word.sort()
print(word)
word.sort(reverse = True)
print(word)
表示イメージ
['1', '2', 'c', 'd', 'f', 'z']
['z', 'f', 'd', 'c', '2', '1']

sorted 組込み関数 (非破壊的)

sorted(iterable, /, *, key=None, reverse=False)

reverse:Trueで降順

word=['z', 'c', 'f', '2','d','1']
print(sorted(word))
print(word)
print(sorted(word,reverse = True))
print(word)

表示イメージ

['1', '2', 'c', 'd', 'f', 'z']
['z', 'c', 'f', '2', 'd', '1']
['z', 'f', 'd', 'c', '2', '1']
['z', 'c', 'f', '2', 'd', '1']

要素追加 append(x)メソッド

list.append(x)

x:追加する要素

word=['a','b']
word.append(11)
print(word)

表示イメージ

['a', 'b', 11]

要素挿入 insertメソッド

list.insert(i, x)

i:インデックス番号
x:要素内容
s += t と同一

word=['a', 'b', 'c', 'd','e']
word.insert(3,'ZZ')
print(word)

表示イメージ

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

要素削除

要素内容で削除 removeメソッド

list.remove(x)

word=['a', 'b', 'c', 'd','e']
word.remove('c')
print(word)
表示イメージ
['a', 'b', 'd', 'e']

インデックス番号で削除+取得 popメソッド

list.pop(i)

i:省略時、末尾を削除+取得
※スタックとして使える。(last-in, first-out)

word=['a', 'b', 'c', 'd','e']
print(word.pop(2))
print(word)
print(word.pop())
print(word)
表示イメージ
c
['a', 'b', 'd', 'e']
e
['a', 'b', 'd']
リストの先頭要素の削除+取得 collections.deque

キューとして使える。(first-in, first-out)

from collections import deque

word=deque(['a', 'b', 'c', 'd','e'])
print(word.popleft())
print(word)

表示イメージ

a
deque(['b', 'c', 'd', 'e'])

インデックス番号で削除 del文

del list[x]

x:インデックス番号
スライスも可能

word=['a', 'b', 'c', 'd','e']
del word[1]
print(word)
word=['a', 'b', 'c', 'd','e']
del word[1:3]
print(word)
表示イメージ
['a', 'c', 'd', 'e']
['a', 'd', 'e']

要素逆順 reverseメソッド

list.reverse()

word=['a', 'b', 'c', 'd','e']
word.reverse()
print(word)

表示イメージ

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

要素copy メソッド

list.copy()

word=['a', 'b', 'c', 'd','e']
copy_word=word.copy()
print(word)
print(copy_word)

表示イメージ

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

文字列→リスト 変換

区切り文字利用 splitメソッド

str.split(sep=None, maxsplit=- 1):前から、文字列分割

文字結合利用 joinメソッド

str.join(iterable):文字列結合

Python 文字列メソッド

文字列メソッド

文字列.メソッド名(引数, ....) の形式の関数のようなもの

変換

文字加工

埋める

寄せる

フォーマット

文字結合

トリミング

分割

置換え

状態

判定

検索

Python - str.zfill(width):長さ指定+0埋め

概要

str.zfill(width)

str:文字列
width:文字長さ。(符号の桁を含む)

  • 長さ指定+0埋め
  • 先頭が符号だった時、符号の後から0埋めする
  • 組込み型 文字列メソッド

実行結果

print("abcde".zfill(10))
print("-abcde".zfill(10))

表示イメージ

 00000abcde
 -0000abcde

Python - str.upper():全大文字に変換

概要

str.upper()

  • 全大文字(大小区別あり)に変換
  • 組込み型 文字列メソッド

実行結果

print("abc123defg".upper())

表示イメージ

ABC123DEFG