【发布时间】:2018-04-04 03:12:20
【问题描述】:
给定元组列表的输入列表:
input_lol = [ [('x', 'AA'), ('y', 'AB')],
[('yy', 'AB'), ('..', 'Punct'), ('foo', 'ZZ')],
[('y', 'AB')]
]
所需的输出是重新组合元组的内部列表,使得在元组的第二个元素中包含'Punct' 的元组被挑出,并且在包含'Punct' 的元组之前的任何元组都被分组到前一个列表中。
例如所需的输出:
desired_lolol = [ [[('x', 'AA'), ('y', 'AB')], [('yy', 'AB')]],
('..', 'Punct'),
[[('foo', 'ZZ')], [('y', 'AB')]]
]
另一个例子:
input_lol = [ [('x', 'AA'), ('y', 'AB')],
[('yy', 'AB'), ('..', 'Punct'), ('foo', 'ZZ')],
[('y', 'AB')],
[('ybar', 'CC')],
[('z', 'NJ'), ('!', 'Punct')],
[('pals', 'AJB')],
]
desired_lolol = [ [[('x', 'AA'), ('y', 'AB')], [('yy', 'AB')]],
('..', 'Punct'),
[[('foo', 'ZZ')], [('y', 'AB')]], [('ybar', 'CC')], [('z', 'NJ')],
('!', 'Punct'),
[('pals', 'AJB')],
]
另一个例子:
input_lol = [ [('x', 'AA'), ('y', 'AB')],
[('yy', 'AB'), ('..', 'Punct'), ('bar', 'YY'), ('..', 'Punct'), ('foo', 'ZZ')],
[('y', 'AB')],
[('ybar', 'CC')],
[('z', 'NJ'), ('!', 'Punct')],
[('pals', 'AJB')],
]
desired_lolol = [ [[('x', 'AA'), ('y', 'AB')], [('yy', 'AB')]],
('..', 'Punct'),
[('bar', 'YY')],
('..', 'Punct'),
[[('foo', 'ZZ')], [('y', 'AB')]], [('ybar', 'CC')], [('z', 'NJ')],
('!', 'Punct'),
[('pals', 'AJB')],
]
我试过了:
desired_lolol = []
output_inner_lol = []
for inner_list_of_tuple in input_lol:
if any(tag == 'Punct' for s, tag in inner_list_of_tuple):
pending = []
for s, tag in inner_list_of_tuple:
if tag == 'Punct':
desired_lolol.append(pending)
desired_lolol.append((s,tag))
pending = []
else:
pending.append((s,tag))
if pending:
desired_lolol.append((s,tag))
else:
desired_lolol.append(inner_list_of_tuple)
得到了这个:
[[('x', 'AA'), ('y', 'AB')],
[('yy', 'AB')],
('..', 'Punct'),
('foo', 'ZZ'),
[('y', 'AB')]]
但[('x', 'AA'), ('y', 'AB')] 和[('yy', 'AB')] 并没有组合到一个列表中。所以我不得不做一些后期处理:
desired_lolol = []
output_inner_lol = []
for inner_list_of_tuple in input_lol:
if any(tag == 'Punct' for s, tag in inner_list_of_tuple):
pending = []
for s, tag in inner_list_of_tuple:
if tag == 'Punct':
desired_lolol.append(pending)
desired_lolol.append((s,tag))
pending = []
else:
pending.append((s,tag))
if pending:
desired_lolol.append((s,tag))
else:
desired_lolol.append(inner_list_of_tuple)
really_desired_lolol = []
pending = []
for x in desired_lolol:
if type(x) == tuple and x[1] == 'Punct':
really_desired_lolol.append(pending)
really_desired_lolol.append(x)
pending = []
else:
pending += x
if pending:
really_desired_lolol.append(pending)
有没有更简单的方法来获取desired_lolol?
【问题讨论】:
-
你能谈谈输入的性质吗,比如 Punct 元组只会在包含它们的子列表中出现一次>?
-
点元组会出现多次。