【发布时间】:2014-11-18 20:00:17
【问题描述】:
我有一个包含一些特定元素的列表。我想根据这些元素将该列表拆分为“子列表”或不同的列表。例如:
test_list = ['a and b, 123','1','2','x','y','Foo and Bar, gibberish','123','321','June','July','August','Bonnie and Clyde, foobar','today','tomorrow','yesterday']
如果元素匹配“某事某事”,我想拆分为子列表:
new_list = [['a and b, 123', '1', '2', 'x', 'y'], ['Foo and Bar, gibberish', '123', '321', 'June', 'July', 'August'], ['Bonnie and Clyde, foobar', 'today', 'tomorrow', 'yesterday']]
到目前为止,如果在特定元素之后有固定数量的项目,我可以做到这一点。例如:
import re
element_regex = re.compile(r'[A-Z a-z]+ and [A-Z a-z]+')
new_list = [test_list[i:(i+4)] for i, x in enumerate(test_list) if element_regex.match(x)]
几乎就在那里,但并不总是紧跟在特定的感兴趣元素之后的三个元素。有没有比循环遍历每个项目更好的方法?
【问题讨论】:
-
看起来您想在
'Foo and Bar, gibberish'上拆分,但您的正则表达式将不匹配(它会在 Bar 之后的逗号上失败)。您是否在任何地方都缺少单引号?'Bonnie and Clyde, foobar'有同样的问题。至于更好的方法,除非您不能连续匹配两个匹配项或存在其他限制,否则您确实需要检查每个条目,因为它可能是新列表的开始。