Skip to content

Instantly share code, notes, and snippets.

@tsuchm
Last active July 1, 2020 21:41
Show Gist options
  • Save tsuchm/30a6e51165e0735f90be4dc1678020d4 to your computer and use it in GitHub Desktop.
Save tsuchm/30a6e51165e0735f90be4dc1678020d4 to your computer and use it in GitHub Desktop.
def skipfalse(iterable):
for elem in iterable:
if elem:
yield elem
foo=['abc', False, 'de']
print(skipfalse(foo))
print(list(skipfalse(foo)))
# filter() と lambda を使うと上記コードと同じことができる.
print(filter(lambda x: x, foo))
print(list(filter(lambda x: x, foo)))
# https://docs.python.org/ja/3/library/functions.html#filter によると,
# 条件式のところに None を指定すると恒等関数を指定したことになるので,
# 上記のコードは以下のように簡略化できる.
print(filter(None, foo))
print(list(filter(None, foo)))
# ジェネレータ式 https://docs.python.org/ja/3/reference/expressions.html?#grammar-token-generator-expression
# を使っても同じことができる.
print((x for x in foo if x))
print(list((x for x in foo if x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment