检查列表中的数字是否可以被某些数字整除? [英] Check what numbers in a list are divisible by certain numbers?

查看:240
本文介绍了检查列表中的数字是否可以被某些数字整除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个函数,它接收一个数字列表
和一个条目列表,并且只返回所有这些条件中可以被整除的元素b b。您必须使用两个嵌套列表解析来解决它。



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):

到目前为止,我有一个模糊的伪代码,包括检查列表,检查是否可以将它附加到新的列表中,检查新的列表检查是否可以被下一个字词整除,直到你经历了所有的条款,我不希望任何人为我做这个,但也许在正确的方向提示?

解决方案

应该检查是否有一个特定的号码,这个数字是可以被第二个列表中的所有条款均匀分割的

  all(i% j == 0 for a_list_of_terms)

然后用外部列表理解来遍历第一个列表

  [我为我在a_list中如果全部(i%j == 0为a_list_of_terms中的j)] 

$ b pre
$ b $ pre $ def $ divisible_numbers (a_list,a_list_of_terms):
return [我为我在a_list如果所有(i%j == 0为j在a_list_of_terms)]

测试

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


Write a function that receives a list of numbers and a list of terms and returns only the elements that are divisible by all of those terms. You must use two nested list comprehensions to solve it.

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

def divisible_numbers(a_list, a_list_of_terms):

I have a vague pseudo code so far, that consists of check list, check if divisible if it is append to a new list, check new list check if divisible by next term and repeat until, you have gone through all terms, I don't want anyone to do this for me but maybe a hint in the correct direction?

解决方案

The inner expression should check if for a particular number, that number is evenly divisible by all of the terms in the second list

all(i%j==0 for j in a_list_of_terms)

Then an outer list comprehension to iterate through the items of the first list

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

All together

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)]

Testing

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

这篇关于检查列表中的数字是否可以被某些数字整除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆