检查列表中哪些数字可以被特定数字整除?

3

编写一个函数,接收一个数字列表和一个术语列表,并返回只能被所有术语整除的元素。您必须使用两个嵌套的列表推导式来解决它。

divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) # 返回 [12, 6]

def divisible_numbers(a_list, a_list_of_terms):

目前我有一个模糊的伪代码,它包括检查列表,检查是否可以整除,如果可以,则将其附加到新列表中,检查新列表是否可以整除下一个术语并重复,直到您遍历了所有术语,我不希望任何人替我完成这项工作,但也许可以给出正确方向的提示?


这里是一个不错的起点 https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions - ILostMySpoon
2个回答

9
内部表达式应该检查特定数字是否可以被第二个列表中的所有项整除。
all(i%j==0 for j in a_list_of_terms)

然后使用外部列表推导式来迭代第一个列表中的项目

[i for i in a_list if all(i%j==0 for j in a_list_of_terms)]

总体而言

def divisible_numbers(a_list, a_list_of_terms):
    return [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]

测试

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

这里很好地运用了所有函数。 - ntough
如果列表很大,您可能需要考虑通过检查术语是否没有公共因数来优化输入。这样您就不会进行不必要的检查。例如,在[2,3,6]中将6作为一个术语进行处理是没有意义的,因为任何可被6整除的数也可被2和3整除。 - dpmcmlxxvi
很好地使用了“all”。如果您将其替换为“any”,那么这是一个有趣的比较案例。 - peterb

0

如果你想用这种方式从用户那里获取输入。

enter code hereprint("numbers which are divisible by 5")
user_input=eval(input("enter the value in list type [1,2,3]: "))**
print(type(user_input)) if type(user_input)==list: for i in
user_input: if(i%5==0): print(i,end=",") else:
    print("none")

输出:

numbers that are divisible by 5 enter the value in list type [1,2,3]:
   [15,10,20,45,69] <class 'list'> 15,10,20,45,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接