Pythonには以下のようなものがありますか?
for item in items #where item>3:
#.....
つまり、Python2.7とPython3.3の両方を一緒に意味します。
Pythonには以下のようなものがありますか?
for item in items #where item>3:
#.....
つまり、Python2.7とPython3.3の両方を一緒に意味します。
You can combine the loop with a generator expression:
for x in (y for y in items if y > 10):
....
itertools.ifilter
(py2) / filter
(py3) is another option:
items = [1,2,3,4,5,6,7,8]
odd = lambda x: x % 2 > 0
for x in filter(odd, items):
print(x)
あなたはこのようなことを意味します:-
item_list = [item for item in items if item > 3]
または、Generator
式を使用することもできます。これは、新しいリストを作成せず、ジェネレーターを返します。ジェネレーターは、yield
メソッドを使用して各反復で次の要素を返します。
for item in (item for item in items if item > 3):
# Do your task
where
質問のような特別な構文はありませんが、他の言語と同様にif
、ループ内でいつでもステートメントを使用できます。for
for item in items:
if item > 3:
# Your logic here
またはガード句 (繰り返しますが、他の言語と同様):
for item in items:
if not (item > 3): continue
# Your logic here
これらの退屈なアプローチはどちらも、このための特別な構文と同じくらい簡潔で読みやすいものです。
Python 3 と Python 2.7 の両方filter()
に、関数 (以下の例ではラムダ関数) が返すリストからアイテムを抽出できる関数がありますTrue
。
>>> nums=[1,2,3,4,5,6,7,8]
>>> for item in filter(lambda x: x>5,nums):
... print(item)
...
6
7
8
の関数を省略すると、に記載されているように、 でfilter()
ある項目のみが抽出されます。True
pydoc filter
明示的なif
ステートメントを使用できます。
for item in items:
if item > 3:
# ...
または、後で繰り返すために名前が必要な場合は、ジェネレーターを作成できます。例:
filtered_items = (n for n in items if n > 3)
または、関数に渡すこともできます:
total = sum(n for n in items if n > 3)
for x in (y for y in items if y > 3):
好みの問題かもしれませんが、上記のオプションと比較して醜いなど、インラインのgenexprと組み合わせたforループを見つけました。