计数 x % y == 0 的出现次数

Jon*_*nis 3 python dictionary

我正在编写一个函数,它接受*args并返回一个从 1 到 9 的键的字典,并确定有多少数字可以被 1 到 9 整除而没有余数:

my_dict = {}
def myFunc(*args):
    for item in args:
        if (item % 2 == 0):
            my_dict[2] = number of times arguments were divisible by 2
                 if (item % 3 == 0):
                     my_dict[3] = number of times arguments were divisible by 3
       ...

myFunc(1,5,6,10,5,8)
Run Code Online (Sandbox Code Playgroud)

我试过这个:

my_dict = {}
def myFunc(*args):
    x=0
    for item in args:
        if (item % 2) == 0:
           x+=1
           my_dict[2] = x
myFunc(1, 2, 3, 6, 8,10)
print(my_dict)
#{2: 4}
Run Code Online (Sandbox Code Playgroud)

这适用于一个数字,不知道我如何优雅地填充整个字典,所以它在1,2,3,4,4,5,10,16,20传递时看起来像这样:

my_dict = {1:9, 2:6, 3:1, 4:4, 5:3, 6:0, 7:0, 8:1, 9:0}
Run Code Online (Sandbox Code Playgroud)

我怎么能解决这个问题?

ste*_*emo 5

a = [1,2,3,4,4,5,10,16,20]

d = {i: sum(k % i == 0 for k in a) for i in range(1,10)}

d
# {1: 9, 2: 6, 3: 1, 4: 4, 5: 3, 6: 0, 7: 0, 8: 1, 9: 0}
Run Code Online (Sandbox Code Playgroud)

或者如果你愿意,

def myfun(*args):
    return {i: sum(k % i == 0 for k in args) for i in range(1,10)}

myfun(1,2,3,4,4,5,10,16,20)
# {1: 9, 2: 6, 3: 1, 4: 4, 5: 3, 6: 0, 7: 0, 8: 1, 9: 0}
Run Code Online (Sandbox Code Playgroud)