【问题标题】:Python: Type error 'float' object is not iterablePython:类型错误'float'对象不可迭代
【发布时间】:2020-04-18 15:03:21
【问题描述】:

我的代码是:

for ep in range(10):
    for x, y in tqdm(train_iterator.gen_batches(batch_size=64, 
                                           data_type="train")):
        x_embed = embedder(tokenizer(str_lower(x)))
        y_onehot = onehotter(classes_vocab(y))
        cls.train_on_batch(x_embed, y_onehot)

结果:

<ipython-input-30-3f8c38399ce9> in <module>()
      2     for x, y in tqdm(train_iterator.gen_batches(batch_size=64, 
      3                                            data_type="train")):
----> 4         x_embed = embedder(tokenizer(str_lower(x)))
      5         y_onehot = onehotter(classes_vocab(y))
      6         cls.train_on_batch(x_embed, y_onehot)

1 frames
/usr/local/lib/python3.6/dist-packages/deeppavlov/models/preprocessors/str_lower.py in str_lower(batch)
     31         return batch.lower()
     32     else:
---> 33         return list(map(str_lower, batch))

TypeError: 'float' object is not iterable

我尝试将其更改为 ep = int [float] 但这也不起作用。

【问题讨论】:

  • You x 属于 float 类型,但它应该是 string 或 python 中存在的其他可迭代类型,例如 list 或 tuple ,我可以从给定的信息中理解。跨度>
  • 感谢您对我的帖子进行评论。但是如何通过我的代码将 x 转换为字符串?
  • 您期望通过迭代tqdm(...) 产生的xy 是什么?我们对您的数据或数据生成器一无所知。为什么x 是一个数字,而其余代码需要一个字符串或字符串列表?不要盲目地在代码中添加补丁 - 专注于理解,而不是补丁。

标签: python for-loop floating-point iterable


【解决方案1】:

str_lower() 将字符串作为参数或可迭代类型并在其上调用 .lower()。但是在您的代码中,x 是浮点类型。 因此,每当使用 x 作为参数调用 list() 时,它都会返回此错误:

>>> list(3.14)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    list(3.14)
TypeError: 'float' object is not iterable

所以你要么想要:

  • 确保x 是一个字符串
  • 不打电话str_lower(x)

【讨论】:

  • 感谢您对我的帖子进行评论。但是如何通过我的代码将 x 转换为字符串?
  • 我不确定你想用你的代码做什么,但你希望 x 是一个字符串吗? embedder(tokenizer(x)) 不行吗?或者您可以使用str(x) 将其转换为字符串,在这种情况下您不需要调用str_lower(),它将是embedder(tokenizer(str(x)))。但同样,我不知道您的代码究竟做了什么。希望这会有所帮助。
猜你喜欢
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 2012-10-30
  • 2020-03-19
  • 2017-03-05
  • 2015-10-23
相关资源
最近更新 更多