出于标准响应的目的,我需要从中转换一个字符串:
[(('Ethyl', 'alcohol'), 1.0), (('clean', 'water'), 1.0)]
Run Code Online (Sandbox Code Playgroud)
对此:
[{"words": "Ethyl,alcohol", "score": 1.0}, {"words": "clean,water", "score": 1.0}]
Run Code Online (Sandbox Code Playgroud)
我能够正确编码,但我的代码似乎不像“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)
Run Code Online (Sandbox Code Playgroud)
我的代码可以接受吗?我将更频繁地处理这个问题,并希望看到一种更易读的 Python 方式。
小智 7
试试这个使用理解:
dataList = [(('Ethyl', 'alcohol'), 1.0), (('clean', 'water'), 1.0)]
[{'words': ','.join(x), 'score': y} for x, y in dataList]
Run Code Online (Sandbox Code Playgroud)
输出:
[{'words': 'Ethyl,alcohol', 'score': 1.0},
{'words': 'clean,water', 'score': 1.0}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |