【问题标题】:Why Am I Getting A Type Error When Running This Function?为什么运行此函数时会出现类型错误?
【发布时间】:2021-03-04 13:30:06
【问题描述】:

我正在尝试创建一个函数,它返回字典中所有值的列表,这些值也是键。但是,我不断在终端中打印出'TypeError:'int'类型的参数不可迭代'。为什么这段代码不起作用?

def values_that_are_keys(my_dictionary):
 for element, numbers in my_dictionary.items():
  if numbers in element:
      print(numbers)

values_that_are_keys({1:100, 2:1, 3:4, 4:10})

【问题讨论】:

  • 因为element 是一个整数。您无法检查某事物是否 in 为整数。

标签: python dictionary for-loop


【解决方案1】:

因为element 是一个整数。您无法检查某事物是否为 in 整数。

如果您想检查numbers(顺便说一下,它不应该是复数)是否是my_dictionary 中的一个键,您需要

if numbers in my_dictionary:
    ...

来自https://docs.python.org/3/library/stdtypes.html#typesmapping

键入 d

如果 d 有一个键 key 则返回 True,否则返回 False。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2019-10-28
相关资源
最近更新 更多