我有一个字典列表,我将使用键和值作为函数的参数传递。该函数对这些键和值进行一些计算。我想实现的是:
dList = [{k1:v1, k2:v2, k3:v3}, {k4:v4, k5:v5}, {k6:v6 k7:v7,k8:v8}]
finalList = [[kv1, kv2, kv3], [kv4,kv5], [kv6,kv7,kv8]]
#kv(number) is the return values of the function
但是我得到的是:
finalList = [kv1,kv2,kv3,kv4,kv5,kv6,kv7,kv8]
如何维护嵌套列表结构?
下面是我的代码:setUpTime = []
dList = []
fList = []
for x in range(len(dList)):
for d in dList:
if d == dList[x]:
for k , v in d.items():
temp = setupTime(k, v)
setUpTime.append(temp)
每次通过外部循环时都需要创建一个内部列表。将函数的结果附加到该列表,然后将该列表附加到最终结果。
finalList = []
for d in dList:
innerList = []
for k, v in d.items():
innerList.append(setupTime(k, v))
finalList.append(innerList)
但是这可以简化为嵌套的列表推导式:
finalList = [[setupTime(k, v) for (k,v) in d.items()]
for d in dList]