【问题标题】:Dictionary comprehension, tuples?字典理解,元组?
【发布时间】:2021-03-21 02:12:48
【问题描述】:

我试图理解

resultList =  [['TWP-883 PASS'], ['TWP-1080 PASS'], ['TWP-1081 PASS']]

result_dicts = [{("issueId","status")[x[0]]:x[1] for x in enumerate(lst[0].split())} for lst in resultList] 

那行代码。试图将这种理解方法扩展到经典方法。

x =((0, 'TWP-883'),(1, 'PASS'),(0, 'TWP-1080'),(1, 'PASS'),(0, 'TWP-1081'),(1, 'PASS'))

bew ={("issueId", "status")[x[0][0]]:x[0][0]}

print(bew)

我快要发疯了,谁能解释一下这个语法?

【问题讨论】:

  • 有更简单和更清晰的方法来实现同样的事情。例如:[dict(zip(('issueId', 'status'), lst[0].split())) for lst in resultList].

标签: python dictionary list-comprehension dictionary-comprehension


【解决方案1】:

您只是要求我们解释发生了什么吗?如果是这样,这里还有另外 2 种写法。

results = []
for i in resultList:
    id, result = i[0].split()
    results.append({"issueId": id, "status": result})
print(results)

res = [{"issueId": x[0], "status": x[1]} for x in [i[0].split() for i in resultList]]
print(res)

【讨论】:

    猜你喜欢
    • 2012-08-19
    • 2021-03-26
    • 1970-01-01
    • 2016-02-27
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多