HW3 <<
Previous Next >> 8.Rock paper sciorrs(剪刀石頭布)
7.List Comprehensions(理解串列)
Kaggle:https://www.kaggle.com/gg542466/hw3-7
Exercise 7 (練習7)
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.
假設我提供給你了一個保存在變量中的列表:a = [1、4、9、16、25、36、49、64、81、100]。編寫一行Python程式,使用此列表a並創建一個僅包含該列表偶數元素的新列表。
Discussion(討論)
Concepts for this week:
本周將應用的概念:
- List comprehensions(理解串列)
List comprehensions(理解串列)
The idea of a list comprehension is to make code more compact to accomplish tasks involving lists. Take for example this code:
理解串列的意思是使代碼更緊湊,以完成涉及列表的任務。以下面的代碼為例:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = []
for year in years_of_birth:
ages.append(2014 - year)
And at the end, the variable ages has the list [24, 23, 24, 24, 22, 23]. What this code did was translate the years of birth into ages, and it took us a for loop and an append statement to a new list to do that.
最後,變量年齡具有列表[24、23、24、24、22、23]。這段代碼所做的就是將出生的歲月轉換成年齡,然後我們使用了for循環,並在新列表中添加了一個append語句來完成此操作。
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = [2014 - year for year in years_of_birth]
The second line here - the line with ages is a list comprehension.
這裡的第二行,帶年齡的行列是理解串列。
It accomplishes the same thing as the first code sample - at the end, the ages variable has a list containing [24, 23, 24, 24, 22, 23], the ages corresponding to all the birthdates.
它完成了與第一個代碼示例相同的操作...最後,ages變量具有一個包含[24、23、24、24、22、23]的列表,這些年齡對應於所有的生日。
The idea of the list comprehension is to condense the for loop and the list appending into one simple line. Notice that the for loop just shifted to the end of the list comprehension, and the part before the for keyword is the thing to append to the end of the new list.
列表理解的想法是壓縮for循環,並將列表追加到一條簡單的行中。注意,for循環剛剛移到列表理解的末尾,而for的關鍵字之前的部分是要附加到新列表末尾的。
You can also embed if statements into the list comprehension - check out this reference to help you out. There are many examples and a better explanation than I can ever give.
你也可以將if語句嵌入列表推導中-請查閱此參考資料以幫助你。有許多例子能比我提供出更好的解釋。
Happy coding!
練習加油!!
個人練習成果:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = []
for num in a:
if num % 2 == 0:
a.append(num)
print(b)
HW3 <<
Previous Next >> 8.Rock paper sciorrs(剪刀石頭布)