from typing import List, Tuple
defnum_lists(nums: List[int])-> Tuple[List[int], List[int], List[int]]: even =[] one_third =[] others =[]for i in nums:match i:case i if i %2==0: even.append(i)case i if i %3==0: one_third.append(i)case_: others.append(i)return even, one_third, others
if __name__ =='__main__':[print(l)for l in num_lists(range(10))]
計算式をcaseに含めたい場合は上記のようにi if i % == 0のように内部で変数化が必要なため、冗長な表現になってしまいます。
クラスでパターンマッチング
続いて、クラスによるパターンマッチングの例です。
match.py
classHuman: has_philosophy:boolclassAnimal: has_instinct:booldefindentify(x):match x:case Human():return"Human"case Animal():return"Animal"case_:return"Unknown"if __name__ =="__main__": obj = Human() obj.has_philosophy =Trueprint(f'I am a {indentify(obj)}') obj = Animal() obj.has_instinct =Trueprint(f'I am an {indentify(obj)}')print(f'I am an {indentify(0)}')
上記の出力結果は以下です。
$ python match.py
I am a Human
I am an Animal
I am an Unknown