python - 如何将此元组列表更改为以下格式?
问题描述
我正在尝试更改以下元组:
[((' "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()
如何更改我的输出写入以获得我想要的格式?
解决方案
从您的文件编写代码来看,您的元组似乎是一致的格式,所以如果这是真的,这是微不足道的:
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]
您知道所有成员在元组中的位置,因此获取您想要的值,删除无关的引号和空格,并将其全部打包到一个字典中。
推荐阅读
- django - 仪表板 url 生成唯一 url 以允许未连接的用户查看特定仪表板
- reactjs - ListItem(Material UI组件)中的React Typescript prop错误
- javascript - 如何使用 mongodb 和 discord.js 制作货币商店
- c# - pdfHTML/iText 7:打印开始/结束行数
对于一个项目,我目前正在编写一个使用 pdfHTML 3.0.3 和 iText 7.1.14 的文档生成器。该文档包含一个显示“项目”的表格。这些项目行可能永远不会真正适合一页,并且在大多数情况下会跨越许多页。
该表的第一列有一个项目编号,可能缺少项目编号(由于项目无效)。
我希望表格显示 中的第一个和最后一个项目编号,在理想
<tfoot>
的- javascript - 如何配置安全性以允许仅通过身份验证访问 swagger-ui url
- qt - 如何正确断开从 QNetworkreply 读取的信号就绪
- wordpress - Woocommerce:如何检查用户是否使用过优惠券?
- spring-boot - 为 Spring 集成应用程序编写测试用例
- python - Python 线程从环境中创建样本
- flutter - 颤动中的幻灯片过渡外观容器