【问题标题】:Dictionary comprehension to find all numbers b/w 1 and 25 that are divisible by a single digit other than 1 (2-9)字典理解以查找所有可以被除 1 (2-9) 之外的单个数字整除的数字 b/w 1 和 25
【发布时间】:2018-08-07 12:42:38
【问题描述】:
d={k:v for k in range(1,25) for v in range(2,9) if k%v==0}
print (d)
d={newdic.setdefault(key,value) for key in range(1,25) for value in range(2,9) if key%value==0}
print (newdic)

以上代码的输出是

{2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 3, 10: 5, 12: 6, 14: 7, 15: 5, 16: 8, 18: 6, 20: 5, 21: 7, 22: 2, 24: 8}
{2: 2, 3: 3, 4: 2, 5: 5, 6: 2, 7: 7, 8: 2, 9: 3, 10: 2, 12: 2, 14: 2, 15: 3, 16: 2, 18: 2, 20: 2, 21: 3, 22: 2, 24: 2}

我正在寻找的是:

{2: 2, 3: 3, 4: 2, 5: 5, 6: 2, 7: 7, 8: 2, 8: 4, 8: 8, 9: 3, 9: 9, 10: 2, 10: 5,  12: 2, 12: 3, 12: 4, ...}

基本上我希望结果集包含每个可以被数字

【问题讨论】:

  • dict 的键应该是唯一的。如果您想使用dict,请使用tuple 或值列表,例如{...8:[2,4,8]...}

标签: python dictionary dictionary-comprehension


【解决方案1】:

字典键在 Python 中必须是唯一的,但是,您可以散列除该键的所有数字的列表:

final_dict = {i:[b for b in range(2, 10) if i%b == 0] for i in range(2, 25)}
final_dict = {a:b[0] if len(b) == 1 else b for a, b in final_dict.items() if b}

输出:

{2: 2, 3: 3, 4: [2, 4], 5: 5, 6: [2, 3, 6], 7: 7, 8: [2, 4, 8], 9: [3, 9], 10: [2, 5], 12: [2, 3, 4, 6], 14: [2, 7], 15: [3, 5], 16: [2, 4, 8], 18: [2, 3, 6, 9], 20: [2, 4, 5], 21: [3, 7], 22: 2, 24: [2, 3, 4, 6, 8]}

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 2014-10-22
    • 2022-10-14
    • 2018-04-10
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多