[英]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.