首页 > 解决方案 > 如何将此元组列表更改为以下格式?

问题描述

我正在尝试更改以下元组:

[((' "business_id": "zPBccKsIHYtLUGFNYIi8Uw"', ' "business_id": "znDUBjt-m2qmXi_p3m3rDA"'), 0.09523809523809523),((' "business_id": "zauhMY78k36XPfxD3GURkQ"', ' "business_id": "zp-K5s3pGTWuuaVBWo6WZA"'), 0.07407407407407407)]

到这种格式:

{'b1': 'zPBccKsIHYtLUGFNYIi8Uw', 'b2': "znDUBjt-m2qmXi_p3m3rDA', 'sim': 0.09523809523809523}

我尝试通过尝试将其更改为 dict 来解决此问题(这是不可能的,因为它不知道如何分配键和值)并列出但似乎没有任何点击。

我目前正在使用 Python 通过以下方式将元组写入输出文件:

fout = open(outfilePath, mode = 'w')
fwriter = csv.writer(fout, delimiter = ',', quoting = csv.QUOTE_MINIMAL)


for pair in similarPairs:
    fwriter.writerow([ str(pair[0][0]), str(pair[0][1]), pair[1]])
fout.close()

我使用 Jaccard Similarity 和 threshold>=0.055 找到了similarPairs:

## Computing the Jaccard Similarity for the candidate pairs.
similarPairs = candidatePairs.map(lambda currPair : computeJC(currPair, ratedBusinessUsers)).filter(lambda f : f[1] >= 0.055).collect()

如何更改我的输出写入以获得我想要的格式?

标签: pythondata-mining

解决方案


从您的文件编写代码来看,您的元组似乎是一致的格式,所以如果这是真的,这是微不足道的:

x = ((' "business_id": "zPBccKsIHYtLUGFNYIi8Uw"', ' "business_id": "znDUBjt-m2qmXi_p3m3rDA"'), 0.09523809523809523)
yy = {}
yy['b1'] = x[0][0].split(':')[1].strip('" ')
yy['b2'] = x[0][1].split(':')[1].strip('" ')
yy['sim'] = x[1]

您知道所有成员在元组中的位置,因此获取您想要的值,删除无关的引号和空格,并将其全部打包到一个字典中。


推荐阅读