我有数据(使用Gensim的LDA结果),如下所示:
[(1, 0.97456828373415116)]
[(0, 0.91883125256489728), (1, 0.020225186991467976), (2, 0.020314851937259213), (3, 0.020382294889184499), (4, 0.020246413617191008)]
[(0, 0.93783520386426555), (1, 0.015481826214088806), (2, 0.015545735781026492), (3, 0.015535246185968628), (4, 0.015601987954650424)]
[(2, 0.98493696818505228)]
[(3, 0.99067359305252778)]
[(0, 0.73578249201070511), (3, 0.25197028613750805)]
我想转换为以下格式:
[(0, 0), (1, 0.97456828373415116), (2, 0), (3, 0), (4, 0)]
[(0, 0.91883125256489728), (1, 0.020225186991467976), (2, 0.020314851937259213), (3, 0.020382294889184499), (4, 0.020246413617191008)]
[(0, 0.93783520386426555), (1, 0.015481826214088806), (2, 0.015545735781026492), (3, 0.015535246185968628), (4, 0.015601987954650424)]
[(0, 0), (1, 0), (2, 0.98493696818505228), (3, 0), (4, 0)]
[(0, 0), (1, 0), (2, 0), (3, 0.96747728928637211), (4, 0)]
[(0, 0), (1, 0), (2, 0), (3, 0.99067359305252778), (4, 0)]
[(0, 0.73578249201070511), (1, 0), (2, 0), (3, 0.25197028613750805), (4, 0)]
答案 0 :(得分:1)
您可以使用<html>
<body>
<p> This is page Two! </p>
</body>
</html>
功能将每个子列表更改为dict
:
map()
然后使用data = [[(1, 0.97456828373415116)],
[(0, 0.91883125256489728), (1, 0.020225186991467976), (2, 0.020314851937259213), (3, 0.020382294889184499), (4, 0.020246413617191008)],
[(0, 0.93783520386426555), (1, 0.015481826214088806), (2, 0.015545735781026492), (3, 0.015535246185968628), (4, 0.015601987954650424)],
[(2, 0.98493696818505228)],
[(3, 0.99067359305252778)],
[(0, 0.73578249201070511), (3, 0.25197028613750805)]]
results = list(map(dict, data))
方法并为字典中不存在的键指定默认值dict.get
:
0
上述结果:
for i in range(5):
print(results[0].get(i, 0))
答案 1 :(得分:1)
一种非常简单的方法是使用带有默认值的构造dict,然后更新它:
>>> d = dict([(0,0),(1,0),(2,0),(3,0)])
>>> print(d)
{0: 0, 1: 0, 2: 0, 3: 0}
>>> d.update([(0, 0.73578249201070511), (3, 0.25197028613750805)])
>>> print(d)
{0: 0.7357824920107051, 1: 0, 2: 0, 3: 0.25197028613750805}
修改强>
结合hgwell的建议来输出元组列表,这里是一个完整的函数(可能会以某种方式更好地完成,但无论如何都可以):
def listify(l):
res = []
for j in l:
d = dict([(0,0),(1,0),(2,0),(3,0),(4,0)])
d.update(j)
res.append(list(d.items()))
return res
并且在行动......
>>> z = listify([[(1, 0.97456828373415116)],
[(0, 0.91883125256489728), (1, 0.020225186991467976), (2, 0.020314851937259213), (3, 0.020382294889184499), (4, 0.020246413617191008)],
[(2, 0.98493696818505228)]])
>>> pprint(z)
[[(0, 0), (1, 0.9745682837341512), (2, 0), (3, 0), (4, 0)],
[(0, 0.9188312525648973),
(1, 0.020225186991467976),
(2, 0.020314851937259213),
(3, 0.0203822948891845),
(4, 0.020246413617191008)],
[(0, 0), (1, 0), (2, 0.9849369681850523), (3, 0), (4, 0)]]