Python随机检查

2024-04-19 07:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

nvm成功了谢谢你的帮助


Tags: nvm
2条回答

一个表达式,如

{n: [d for d in range(2,10) if n%d==0] for n in randNum}

会给您一个字典,其中键nrandNum中的每个数字,值是n的除数列表,范围为2..9

下面是一个函数的示例,它遍历随机样本并检查所提供范围内每个数字的可除性。此函数返回可以轻松转换为字典的元组列表。你知道吗

import random

random.seed(8675309)

numbers = random.sample(range(100,999), 5)
divisible_by = [2,3,4,5,6,7,8,9]

def check_divisibility(numbers=numbers, divisible_by=divisible_by):
    nums_and_divisors = []
    for i in numbers:
        divisors = []
        for j in divisible_by:
            if i % j == 0:
                divisors.append(j)
        nums_and_divisors.append((i, divisors))

    return nums_and_divisors

answer = check_divisibility(numbers=numbers, divisible_by=divisible_by)

# print(answer)
# [(511, [7]), (319, []), (622, [2]), (779, []), (616, [2, 4, 7, 8])]

dictionary = {key: value for key, value in answer}

# print(dictionary)
# {511: [7], 319: [], 622: [2], 779: [], 616: [2, 4, 7, 8]}

相关问题 更多 >