Python 3.10 で構造パターン マッチングを使用して、未知の長さのシーケンス内の未知の位置にある要素を一致させる賢い方法はありますか?
以下は、私がやりたいことを示す非動作例です。
match [1, 2, "3", 4, 5]:
case [*before, str() as str_found, *after]:
print(f"Found string: {str_found}")
ガード句を使用しようとすると、一致がキャプチャされません。
match [1, 2, "3", 4, 5]:
case [*elem] if any(isinstance(el, str) for el in elem):
print("Found string, but I can't tell you its value.")
長さがわかっている場合は、 or パターンを使用できますが、きれいではありません。
match [1, 2, "3"]:
case [*_, str() as str_found] | [str() as str_found, *_] | [_, str() as str_found, _]:
print(f"Found string: {str_found}")
構造パターン マッチングに関する他の質問への回答とコメントに基づいて、構造パターン マッチングはこの仕事に適したツールではないことを知らせる多くの回答が予想されます。私の例では、単純な for ループのようなものとは対照的に、これに構造パターン マッチングを使用する利点を示していないことはわかっていますが、ネストされた dict とjson.load()
. いずれにせよ、私の質問は適切なツールが何であるかではなく、単にこのツールでそれができるかどうかです.