列表理解字典

时间:2020-07-14 12:41:29

标签: python list-comprehension

一个练习要求我写一个列表理解(键应该被2整除并且在0-10范围内;每个键的值应该等于键的平方)返回以下输出。

my_dict = { (write code here) for num in (write code here) if (write code here)}

我尝试了以下代码,但显然犯了一些错误。

my_dict = {num**2 for num in range(0,10) if float(num/2)==False}
my_dict

你们中的任何人都可以帮助我理解应该怎么做吗?

非常感谢

1 个答案:

答案 0 :(得分:0)

尝试

my_dict = {num : num ** 2 for num in range(10) if num % 2 == 0}
print(my_dict)

输出

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
相关问题