0
1

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 1 year has passed since last update.

【Python】文字列のリストから別のリストの要素を含む文字列を抽出する方法

Posted at

環境

  • conda 4.12.0
  • Python 3.8.12.final.0

コード

例)リスト fruits からリスト filter の要素(=ア, イ, ウ, エ, オ)を含む文字列を抽出する。抽出後のリストを fruits_filtered とする。

py
fruits = ["リンゴ", "イチゴ", "バナナ", "ブドウ", "ミカン", "キウイ", "アンズ"]
filter = ["", "", "", "", ""]
fruits_filtered = [f for f in fruits if any((str in f) for str in filter)]
print(*fruits_filtered)  # イチゴ ブドウ キウイ アンズ

コードの解説

内包表記

内包表記の例
# 内包表記
odds = [i for i in range(10) if i % 2 == 1]

# 等価なコード
odds = []
for i in range(10):
    if i % 2 == 1:
        odds.append(i)

any(iterable)

iterable のいずれかの要素が真ならば True を返す。iterable が空なら False を返す。

any(iterable)の挙動
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

参考

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?