簡體   English   中英

清單理解有問題

[英]Having an issues with list comprehension

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'

我正在嘗試獲取可以被兩個術語整除的索引列表。 我對自己得到的錯誤感到困惑,對列表理解很陌生的人將不勝感激。

你很近。 此代碼應工作:

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 ... 另一個在all內部:項的x % term == 0 for term in terms

您的列表理解能力很好,但是您不小心將一些東西放在方括號中,例如[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
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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM