我将以下数据结构作为JSON对象返回:
[[[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]]]]]]]]
我在将此结构转换为字典时遇到问题。该字典有一组元组作为键,由上述嵌套列表中的文本对象组成(即('assist', u'cross')
)。我用来做这个的代码是:
for match in responser:
for num_events, team, events in match:
regex = {tuple(sub[:2]): sub[2][0] for y in events[0] for sub in y}
然而,这会返回以下错误:
exceptions.TypeError: 'float' object is not iterable
原因似乎是值6.125,
。如何从嵌套列表结构中删除它,但保持相同数量的括号以允许从嵌套列表转换为字典的代码继续工作?
由于
答案 0 :(得分:1)
如果查看变量事件,则无法迭代浮点数:
events[0] = [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]]]]
注意元素0 = 6.125
将代码更改为:
regex = {tuple(sub[:2]): sub[2][0] for y in events[0][1:] for sub in y}
注意事件的规范 - 将跳过元素0并完成所有其余的事情。
正则表达式的输出是:
{(u'assist', u'cross'): 3,
(u'assist', u'short'): 5,
(u'assist', u'throughball'): 1,
(u'normal', u'cross'): 198,
(u'normal', u'longball'): 326,
(u'normal', u'short'): 4726,
(u'normal', u'throughball'): 35}
答案 1 :(得分:1)
一旦你进入内循环,你总是可以改变events
。这将缩短regex
所需的列表理解。
responser = [[[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]]]]]]]]
for match in responser:
for num_events, team, events in match:
events = events[0][1]
regex = {tuple(e[:2]): e[2][0] for e in events}
print regex
### Prints the following.
###{(u'normal', u'short'): 4726, (u'normal', u'cross'): 198, (u'assist', u'short'): 5, (u'normal', u'throughball'): 35, (u'normal', u'longball'): 326, (u'assist', u'throughball'): 1, (u'assist', u'cross'): 3}
答案 2 :(得分:1)
这不是最优雅的解决方案,我敢肯定,但我喜欢这个问题,所以我决定玩一玩......这个函数以递归方式从嵌套的可迭代容器中删除所有浮点数:
def removeFloat(container):
if hasattr(container, '__iter__'):
elementsToRemove = []
for item in container:
if isinstance(item, float):
elementsToRemove.append(item)
for item in elementsToRemove:
container.remove(item)
for item in container:
removeFloat(item)
答案 3 :(得分:0)
您可以更改事件[0]的事件[0] [1]。此外,您不希望在每个y内迭代:
In [31]: for match in responser:
for num_events, team, events in match:
print {tuple(y[:2]): y[2][0] for y in events[0][1]}
....:
{(u'normal', u'short'): 4726, (u'normal', u'cross'): 198, (u'assist', u'short'): 5, (u'normal', u'throughball'): 35, (u'normal', u'longball'): 326, (u'assist', u'throughball'): 1, (u'assist', u'cross'): 3}