skip to content
barorin&?

ifとforを混ぜたリスト内包表記の書き方

/ 1 min read

はじめに

これを一行のPythonコードで書きたい!

columns = ['I am Sam', 'She is Erica', 'He is Eric']
lst = []
for c in columns:
    if 'Sam' in c:
        lst.append(c)

print(lst)
# ['I am Sam']

方法

lst = [c for c in columns if 'Sam' in c]