Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
正規表現文字列を含まないリスト内のすべてのアイテムを削除することは可能ですか?
正規表現の文字列だけを返すことを考えていました。正規表現がない場合は、リストアイテムを空にしてから、リストをもう一度繰り返して空のエントリをすべて削除するのは非効率的です。
何かご意見は?
たとえば、私が持っているとしましょう:
["cat", "dog", "monkey", "Fred", "sad"]
そして私は悲しいものだけを選択する正規表現を書きます。他のすべてを(できれば)削除してほしい。
これを行う最も簡単な方法は、リスト内包表記を使用して新しいリストを作成することです。
regex = re.compile(...) new_list = [s for s in old_list if regex.match(s)]
または、次を使用しfilter()ます。
filter()
new_list = filter(regex.match, old_list)