python中的keys()操作说明?

2024-04-20 09:53:42 发布

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

我不明白这段代码的最后一行到底是怎么需要的,有人能解释一下吗?提前谢谢

ops = {'+': operator.add,'-': operator.sub,'*': operator.mul} #creating a dictioanry, using 'operators' built in functions

keys = list(ops.keys()) # ['+', '*', '-'] list The method keys() returns a list of all the available keys in the dictionary.
opt = random.choice(keys)  #e.g. '+'  randomly choose an operator/key/ from the dictionary
operation = ops[opt]

Tags: the代码increatingadddictionarykeysoperator
2条回答
  • 是一本字典
  • opt是一个随机键

如果opt=“+”,则ops[opt]=operator.add

你应该看看python词典

实际上,你不需要最后一行。您可以只使用“ops[opt]”,只要您考虑使用“operation”

相关问题 更多 >