【问题标题】:exceptions.TypeError: 'float' object is not iterable with nested JSON listexceptions.TypeError:'float' 对象不可与嵌套的 JSON 列表迭代
【发布时间】:2014-10-19 20:00:48
【问题描述】:

我有一个通过 XHR 请求返回的 JSON 对象,它采用以下格式:

[[[13, u'Arsenal', [[[[u'goal', u'openplay', u'header', [1]], [u'goal', u'openplay', u'leftfoot', 
[1]], [u'goal', u'openplay', u'rightfoot', [3]], [u'goal', u'owngoal', u'rightfoot', [1]], [u'miss', 
u'corner', u'header', [2]], [u'miss', u'corner', u'leftfoot', [3]], [u'miss', u'corner', u'rightfoot',
[2]], [u'miss', u'crossedfreekick', u'rightfoot', [2]], [u'miss', u'directfreekick', u'leftfoot', [1]],
[u'miss', u'openplay', u'header', [2]], [u'miss', u'openplay', u'leftfoot', [16]], [u'miss', 
u'openplay', u'rightfoot', [23]]]]]]

responser 是上面的 JSON 对象,我使用以下代码将此嵌套列表转换为 Python 字典,其中字典键为元组:

 for match in responser: 
                    for num_events, team, events in match:

                        regex = {tuple(sub[:3]): sub[3][0] for y in events[0] for sub in y}

但是,当我尝试在下面的嵌套列表中使用相同的对象时:

    [[[13, u'Arsenal', [[6.125, [[u'assist', u'cross', [3]], [u'normal', u'cross', [198]], [u'normal',
 u'longball', [326]], [u'assist', u'short', [5]], [u'normal', u'short', [4726]], [u'assist', 
u'throughball', [1]], [u'normal', u'throughball', [35]]]]]]

我收到以下错误:

exceptions.TypeError: 'float' object is not iterable

谁能告诉我我在这里做错了什么?我可以看到第二个示例中的 JSON 嵌套列表在结构上与第一个略有不同,但我不确定如何修改我的代码以适应这一点,或者具体为什么我会收到此错误。

谢谢

【问题讨论】:

    标签: python json list nested-lists


    【解决方案1】:

    这是因为 6.125 值:您的代码没有说明它的存在。此外,每个迷你列表有 2 个项目而不是 3 个,代码需要相应调整。

    我让它工作的唯一方法就是把它分解成碎片。您不想在列表/字典理解中塞入太多东西:

    这是我转换第一个列表的代码:

    >>> d = {}
    >>> for a in responser[2][0][0]:
    ...   d.update({tuple(a[:3]): a[3][0]})
    

    这是我转换第二个列表的代码。 “1”是获取6.125值之后的项目。并将“3”元素更改为“2”:

    >>> d = {}
    >>> for a in responser[2][0][1]:
    ...   d.update({tuple(a[:2]): a[2][0]})
    ...
    

    【讨论】:

    • 您好,感谢您的回复。这个答案给了我一个索引超出范围的错误消息。
    • 请注意我已经修改了我的答案,因为我的 json 对象包含一个错字,在该对象的开头没有足够的左括号。我不确定这是否会影响你的回答?
    • 嗯,实际上它以前对我有用,但现在没有足够的右括号。你可以试试这个网站看看它是否有效。 jsonformatter.curiousconcept.com(去掉u,把'改成",先去掉回车)
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2016-08-12
    相关资源
    最近更新 更多