HW3 <<
Previous Next >> 11:Check Primality Functions 檢查基本功能
10:List Overlap Comprehensions 列表重疊理解
Exercise 10 (and Solution) 練習10(和解決方案)
This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way.
本週的練習將重溫舊的練習(請參閱練習5),但需要以其他方式解決。
Take two lists, say for example these two 拿兩個列表,舉例來說,這兩個 :
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python using at least one list comprehension. (Hint: Remember list comprehensions from Exercise 7).
並編寫一個程序,該程序返回一個列表,該列表僅包含列表之間的公共元素(無重複項)。 確保您的程序可以在兩個不同大小的列表上運行。 至少使用一個列表理解功能,用一行Python編寫此代碼。 (提示:請記住練習7中的列表理解)。
The original formulation of this exercise said to write the solution using one line of Python, but a few readers pointed out that this was impossible to do without using set
s that I had not yet discussed on the blog, so you can either choose to use the original directive and read about the set
command in Python 3.3, or try to implement this on your own and use at least one list comprehension in the solution.
此練習的原始表述是使用一行Python編寫解決方案,但是一些讀者指出,如果不使用我在博客上尚未討論過的集,這是不可能做到的,因此您可以選擇使用 原始指令,並了解Python 3.3中的set命令,或者嘗試自己實現該指令並在解決方案中至少使用一個列表理解。
Extra 額外 :
• Randomly generate two lists to test this
隨機生成兩個列表進行測試
Discussion 討論區
Concepts for this week 本週的概念 :
• List comprehensions
清單理解
• Random numbers, continued
隨機數,續
List comprehensions 清單理解
We already discussed list comprehensions in Exercise 7, but they can be made much more complicated.
我們已經在練習7中討論了列表理解,但是可以使它們複雜得多。
For example 舉例 :
x = [1, 2, 3]
y = [5, 10, 15]
allproducts = [a*b for a in x for b in y]
At the end of this piece of code, allproducts
will contain the list [5, 10, 15, 10, 20, 30, 15, 30, 45]
. So you can put multiple for loops inside the comprehension. But you can also add more complicated conditionals :
在這段代碼的最後,所有產品都將包含列表[5、10、15、10、20、30、15、30、45]。 因此,您可以在理解中放入多個for循環。 但是您還可以添加更複雜的條件:
x = [1, 2, 3]
y = [5, 10, 15]
customlist = [a*b for a in x for b in y if a*b%2 != 0]
Now customlist
contains [5, 15, 15, 45]
because only the odd products are added to the list.
現在,customlist包含[5、15、15、45],因為只有奇數產品被添加到列表中。
In general, the list comprehension takes the form:
通常,列表理解採用以下形式:
[EXPRESSION FOR_LOOPS CONDITIONALS]
[EXPRESSION FOR_LOOPS條件]
as shown in the examples above.
如以上示例所示。
Random numbers, continued 隨機數,續
Try to use the Python random documentation to figure out how to generate a random list. As a hint look below:
a = random.sample(range(100), 5)
This line of code will leave a
containing a list of 5 random numbers from 0 to 99.
嘗試使用Python隨機文檔來弄清楚如何生成隨機列表。 提示如下: 一個= random.sample(range(100),5) 這行代碼將保留一個包含從0到99的5個隨機數的列表。
Happy coding! 祝您編碼愉快!
HW3 <<
Previous Next >> 11:Check Primality Functions 檢查基本功能