【发布时间】:2018-10-24 12:17:45
【问题描述】:
我正在尝试根据条件从另一个列表创建一个新列表:
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
每当代码出现在包含“#”的元组之后的元组上时,我都需要将正确的行传输到程序的另一部分并重置以开始处理另一行。我设置了一系列条件,得到了这样的结果:
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
我需要再次过滤什么条件?
我不够熟练,无法使用列表解析或内置过滤器,我希望尽可能让代码更具可读性(对于新手而言),至少在我了解更多信息之前。
更新:
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'元组配对,可以省略。
我正在努力解决问题,我会尽快更新我的帖子。
【问题讨论】:
标签: python python-2.7 list filter conditional-statements