如何以 python 方式翻译此工作代码

出于标准响应的目的,我需要从中转换字符串:


[(('Ethyl', 'alcohol'), 1.0), (('clean', 'water'), 1.0)]

对此:


[{"words": "Ethyl,alcohol", "score": 1.0}, {"words": "clean,water", "score": 1.0}]

我能够正确编码,但我的代码看起来不像“pythony”。这是我的代码:


lst = []

for data in dataList:

    dct = {}

    dct['words'] = data[0][0] + ',' + data[0][1]

    dct['score'] = data[1]

    lst.append(dct)


sResult = json.dumps(lst)

print(sResult)

我的代码可以接受吗?我会更频繁地处理这个问题,并希望看到一种更可读的 python 方式。


天涯尽头无女友
浏览 110回答 2
2回答

有只小跳蛙

使用理解来尝试这个:dataList = [(('Ethyl', 'alcohol'), 1.0), (('clean', 'water'), 1.0)][{'words': ','.join(x), 'score': y} for x, y in dataList]输出:[{'words': 'Ethyl,alcohol', 'score': 1.0}, {'words': 'clean,water', 'score': 1.0}]

汪汪一只猫

您可以使用两种方法来缩短代码,这两种方法肯定不会更具可读性,但这是首选方法:内联字典构造lst = []for data in dataList:    lst.append({'words': data[0][0] + ',' + data[0][1], 'score' : data[1]})使用列表理解 lst = [{'words': data[0][0] + ',' + data[0][1], 'score': data[1]} for data in dataList]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python