如何用python的方式翻译这些工作代码



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

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

到此:

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

我能够正确地编码它,但我的代码似乎不像";蟒蛇;。。这是我的代码:

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方式。

尝试使用理解:

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}]

可以用来缩短代码的两种方法是

  • 内联dict构造

    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]
    

最新更新