知りたいことは下のⅣにあります
Ⅰ.
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
Write this in one line of Python.
Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
(問題のリンク内容)
という問題があり
Ⅱ.
コメント欄にはこれでおkというものがありました
print([aa for aa in a if aa < 5])
~以下解説~
What this means is that I'm outputting the variable 'aa' which refers to each item in the list (a).
Since 'aa' is set to refer to each item in list (a), the output will print the items in list (a). However, I also have a filter specified at the end of the code "if aa < 5".
This means that only the items in the list (referred to as aa) that are below 5 are printed out.
It does help if you use labels that are more intuitive in your code. For example instead of naming the list a, I can name the list "number_list":
~終了~
Ⅲ.
~翻訳~
リストの内包表記は次のように振舞います:[list]の[item]に対する[output] if [filter]
ご覧のとおり、その構文には4つのコンポーネントがあります。
出力、アイテム、リスト、およびフィルタ。
上のコードを書いた人の場合[aaに対するaaのaa <aa <5]:
output = aa
item = aa
list = a
filter = aa <5
これが意味するのは、リスト(a)の各項目を参照する変数 'aa'を出力しているということです。
'aa'はlist(a)の各項目を参照するように設定されているので、出力はlist(a)の項目を出力します。ただし、コードの末尾に「if aa <5」と指定したフィルタもあります。
これは、5以下のリストの項目(aaと呼ばれる)だけが印刷されることを意味します。
あなたのコードの中でもっと直感的なラベルを使用するなら、それは役に立ちます。たとえば、リストに名前を付ける代わりに、リストに "number_list"という名前を付けることができます。
~翻訳終了~
Ⅳ.
google翻訳してなるほどと感心したものの、今まで学習してきたものでこのような使い方をすることは初めてでした。
技術はどんどん新しくなるというものはこういうことなのか、と考えつつ。
最新情報のありそうなPythonのリファレンスを見たのですがこのような説明は自分が見た限り見つけることができませんでした。
Pythonリファレンスのリンク内容
自分の知りたいこととしては、どこでこのような文法の構造を知ることができるのか?ということです。
質問が稚拙で申し訳ないです...
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/24 04:33
2019/04/24 04:35
2019/04/24 04:38
2019/04/24 04:45