2016-07-14 33 views
-1
def divisble_numbers(a_list, terms): 
    b_list = [x for x in [a_list] if (x % [terms] == 0)] 
    c_list = [x for x in b_list if all(x % [terms] == 0)] 
    return c_list 

divisble_numbers([2,3,5,1,6,7,8,9,10,11,12], [2,3])   

返回此錯誤:TypeError: unsupported operand type(s) for %: 'int' and 'list'有一個問題與列表理解

我試圖去得到那個是兩個術語整除的索引列表。我對我遇到的錯誤感到困惑,對列表理解很陌生會感謝任何幫助。

+1

一個帶有列表的整數的mod應該等於什麼? 'x%[term]'應該給你什麼? –

回答

2

你非常接近。此代碼應該工作:

def divisble_numbers(a_list, terms): 
    return [x for x in a_list if all(x % term == 0 for term in terms)] 

print(divisble_numbers([2,3,5,1,6,7,8,9,10,11,12], [2,3])) 

# Output: 
# [6, 12] 

有兩個列表解析發生在這裏。一個是x for x in a_list if ...。另一個是allx % term == 0 for term in terms

+0

謝謝,快速問題爲什麼我們需要第二個for循環?我雖然所有的功能會迭代通過列表? – Landon

+0

'all'通過迭代器並確保其中的所有內容都是真實的。所以首先你需要一個迭代器來覆蓋所有的術語,當'x'被這個術語整除時,這個術語表示'真'。用術語'x%term == 0給你這樣的事情。 – smarx

+0

再次感謝您 – Landon

0
b_list = [x for x in a_list if x%(reduce(lambda x,y : x*y, terms))==0] 

輸入:

a_list, terms = [2,3,5,1,6,7,8,9,10,11,12], [2,3] 

輸出:

[6, 12] 

你的功能將是:

def divisble_numbers(a_list, terms): return [x for x in a_list if x%(reduce(lambda x,y : x*y, terms))==0] 
+0

我相信這段代碼實際上是不正確的。例如。嘗試'a_list,terms = [4],[2,4]'。 – smarx

2

你的列表解析都不錯,但你不小心包裹方括號中的東西很少,例如作爲[terms],這不需要是因爲它們已經是列表。 [terms]將產生一個包含列表的列表。

其次,你得到的錯誤是因爲你正在使用列表的mod(%)。 mod運算符僅在數字之間起作用。

def divisble_numbers(a_list, terms): 
    b_list = [x for x in a_list if (x % terms[0] == 0)] 
    c_list = [x for x in b_list if (x % terms[1] == 0)] 
    return c_list 
+0

請注意,該函數將返回列表中第二項可整除的數字列表。 (實際上,你可以刪除'b_list = ...'行,因爲它的結果完全被忽略了。) – smarx