提问人:Arif Rashed 提问时间:11/16/2022 最后编辑:funnydmanArif Rashed 更新时间:11/16/2022 访问量:30
将函数运行到嵌套列表的内部列表元素,并在保持嵌套列表结构的同时附加输出
run function to element of inner list of a nest list and append the output while maintaining the nested list structure
问:
我有一个字典列表,我将使用键和值作为函数的参数传递。该函数对这些键和值进行一些计算。我想实现的是:
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)
答:
1赞
Barmar
11/16/2022
#1
每次通过外部循环都需要创建一个内部列表。将函数的结果追加到该列表中,然后将该列表追加到最终结果。
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]
评论
finalList = [[setupTime(k, v) for (k,v) in d.items()] for d in dList]
setupTime(k, v)
for x in range(len(dList)):
for d in dList: