0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python AND検索 OR検索

Last updated at Posted at 2017-12-08

AND検索

検索文字列はリストで渡す
検索文字列が対象文字列にあったら1,なければ0として結果リストにする
全て1であれば(全要素掛け合わせて1であれば)True

code
from functools import reduce

def search_and(search_words, target_string):
    result_list = [ 1 if i in target_string else 0 for i in search_words ]
    result = reduce(lambda x, y: x*y, result_list)
    return True if result == 1 else False
実行結果
>>> print(search_and(['a','b'], 'abcde'))
True
>>> print(search_and(['a','b','f'], 'abcde'))
False

OR検索

ほぼ同じ。最後に全て0であれば(全要素足し合わせて0であれば)False

code
from functools import reduce

def search_or(search_words, target_string):
    result_list = [ 1 if i in target_string else 0 for i in search_words ]
    result = reduce(lambda x, y: x+y, result_list)
    return False if result == 0 else True
実行結果
>>> print(search_or(['a','b','f'], 'abcde'))
True
>>> print(search_or(['f','g','h'], 'abcde'))
False

検索自体はinでやってるので、高度なことをしたければfindやre.matchとかでどうぞ。

どうでもいいやつ

python3この頃使い始めたけど、reduceはモジュール読み込まないといけなくなったのか。

0
3
1

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?