基于条件从列表生成新列表的问题及优化需求
基于条件从列表生成目标列表的问题
我正尝试基于条件从一个列表生成新列表:
lst = [("Id01","Code1",1),("Id01","#instr1",1),("Id01","#instr2",1),("Id01","#instr4",1), ("Id01","Code2",1),("Id01","#instr3",1),("Id01","#instr2",1),("Id02","Code2",1), ("Id02","#instr2",1),("Id02","#instr5",1)] table, instrlist = '', ''; code, instructions = [], []; qty = 0 for idx, l in enumerate(lst): table = l[0] if not l[1].startswith('#'): code = l[1]; qty = l[2]; instructions = [] else: instructions.append(l[1]) print idx, table, code, instructions, qty
每当包含#的元组之后出现含code的元组时,我需要将正确的行传递到程序的另一部分并重置以处理下一组。我设置了一系列条件后得到如下结果:
0 Id01 Code1 [] 1 1 Id01 Code1 ['#instr1'] 1 2 Id01 Code1 ['#instr1', '#instr2'] 1 3 Id01 Code1 ['#instr1', '#instr2', '#instr4'] 1 4 Id01 Code2 [] 1 5 Id01 Code2 ['#instr3'] 1 6 Id01 Code2 ['#instr3', '#instr2'] 1 7 Id02 Code2 [] 1 8 Id02 Code2 ['#instr2'] 1 9 Id02 Code2 ['#instr2', '#instr5'] 1
但我真正需要的结果是:
3 Id01 Code1 ['#instr1', '#instr2', '#instr4'] 1 6 Id01 Code2 ['#instr3', '#instr2'] 1 9 Id02 Code2 ['#instr2', '#instr5'] 1
我需要添加什么过滤条件?我目前还不熟练使用列表推导式或内置filter函数,希望代码尽可能易读(适合新手),至少在我学到更多知识前保持如此。
更新:尝试的解决方案及问题
jpp提供的解决方案似乎高效且易读:
from collections import defaultdict from itertools import count, chain lst = [("Id01","Code1",1),("Id01","#instr1",1),("Id01","#instr2",1),("Id01","#instr4",1), ("Id01","Code2",1),("Id01","#instr3",1),("Id01","#instr2",1),("Id02","Code2",1), ("Id02","#instr2",1),("Id02","#instr5",1)] d = defaultdict(list) enums = [] c = count() for ids, action, num in lst: if not action.startswith('#'): my_ids, my_action = ids, action enums.append(next(c)) else: d[(my_ids, my_action)].append([action, num]) next(c) enums = enums[1:] + [len(lst)] for idx, ((key1, key2), val) in enumerate(d.items()): print (enums[idx]-1, key1, key2, list(chain.from_iterable(val)), val[0][-1])
但我遇到了一些问题:
- 输出顺序错误(最后一行变成了第一行),结果如下:
(3, 'Id02', 'Code2', ['#instr2', 1, '#instr5', 1], 1) <--- 应该是最后一行 (6, 'Id01', 'Code1', ['#instr1', 1, '#instr2', 1, '#instr4', 1], 1) (9, 'Id01', 'Code2', ['#instr3', 1, '#instr2', 1], 1) - 元组中的数值字段不总是1,当前脚本未正确匹配该数值,需与Code元组关联,可省略无关数值。
我正在解决这些问题,会尽快更新帖子。
内容的提问来源于stack exchange,提问作者Federico Leoni
相关产品推荐
相关产品推荐

