字典理解找到所有数字b / w 1和25,可以被除1(2-9)之外的单个数字整除

时间:2018-02-27 18:51:43

标签: python dictionary dictionary-comprehension

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, ...}

基本上我希望结果集包含每个可被数字< 9整除的数字。示例:由于8可以被2,4和8整除,因此它有3个条目。

1 个答案:

答案 0 :(得分:0)

字典键在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]}