【问题标题】:Why is 'float' object is not iterable?为什么“浮动”对象不可迭代?
【发布时间】:2021-05-16 02:01:30
【问题描述】:

我很难理解为什么我在运行以下代码时收到错误 TypeError: 'float' object is not iterable

traces = [[ -122.29175806045532, 37.809512710254495 ],
           [ -122.29154348373412, 37.810233196634634 ],
           [ -122.29129672050475, 37.810996056903875 ],
           [ -122.29098558425902, 37.811801289748544 ],
           [ -122.29082465171813, 37.81219966485621 ],
           [ -122.2902774810791, 37.812106428321556 ],
           [ -122.28985905647279, 37.81201319166914 ] ]

for trace in traces:
    s = ";".join(map(lambda y: ",".join(str(x) for x in y), trace))

【问题讨论】:

  • 也许把你的oneliner写成传统的for循环,你会看到的。
  • trace 类似于[1.2, 1.3],所以y 类似于1.2。您正在迭代 y (str(x) for x in y),这没有意义。

标签: python loops for-loop typeerror


【解决方案1】:

这很简单。你将如何迭代一个数字?您可以遍历浮点数列表,但不能遍历单个浮点数。循环 3 次时你走得太深了。您正在一个来自循环的映射 lambda 函数内部循环(这就像执行 3 个循环,而您需要 2 个)。

取出一个循环就可以了

【讨论】:

    【解决方案2】:

    代码没问题,但你不需要外部 for 循环。所以,只需删除行 for trace in traces: 并在此处将trace 修复为traces

    s = ";".join(map(lambda y: ",".join(str(x) for x in y), trace))

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2023-03-09
      • 2014-03-16
      • 1970-01-01
      • 2011-12-28
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多