如何在Power Query中循环迭代表格,实现逐次Funct1函数转换?
问题解决:Power Query 中使用 List.Accumulate 迭代处理表格
需求描述
将主表格(MainTable)按列表(ListofItems)中的N个项依次通过函数(Funct1)处理,每次以上一次处理得到的新表格作为下一次函数输入,最终生成最终表格。
尝试情况
- 使用
List.Generate仅能生成列表,无法直接得到最终表格 - 使用
List.Accumulate时,不清楚如何将新表格回传给下一次迭代,当前代码如下:
let MainTable = #"MainTable", Source2 = #"TableofList", TotalRow = Table.RowCount(Source2), ListofItem = Source2[Column1], output = List.Accumulate( {0..TotalRow}, [Item=0,NewTable=MainTable], (result, count) => (NewTable as table)=> let Item=ListofItem{count}, NewTable = Funct1(Item,NewTable) in NewTable ) in output
问题分析
你的代码存在两个核心问题:
List.Accumulate的初始值是一个记录[Item=0,NewTable=MainTable],但迭代函数返回的是一个函数而非记录,导致类型不匹配- 迭代范围
{0..TotalRow}会多遍历一次(行索引从0开始,TotalRow是总行数,正确范围应该是{0..TotalRow-1})
修正后的代码
let MainTable = #"MainTable", Source2 = #"TableofList", ListofItem = Source2[Column1], output = List.Accumulate( ListofItem, // 直接遍历Item列表,无需手动处理索引 MainTable, // 初始值设为原始表格 (currentTable, currentItem) => Funct1(currentItem, currentTable) ) in output
代码说明
- 直接将
ListofItem作为List.Accumulate的第一个参数,省去索引处理的繁琐 - 初始值设为
MainTable,作为第一次迭代的输入表格 - 迭代函数接收两个参数:
currentTable(上一次处理后的表格)和currentItem(当前要处理的项),调用Funct1后直接返回新表格,自动传递给下一次迭代 - 最终
output就是经过所有项处理后的最终表格
如果必须通过索引遍历(比如需要用到索引值),可以修改为:
let MainTable = #"MainTable", Source2 = #"TableofList", TotalRow = Table.RowCount(Source2), ListofItem = Source2[Column1], output = List.Accumulate( {0..TotalRow-1}, // 修正索引范围,避免越界 MainTable, (currentTable, count) => Funct1(ListofItem{count}, currentTable) ) in output
内容的提问来源于stack exchange,提问作者Wait
相关产品推荐
相关产品推荐

