The tuples inside the file:
(\'Wanna\', \'O\')
(\'be\', \'O\')
(\'like\', \'O\')
(\'Alexander\', \'B\')
(\'Coughan\', \'I\')
(\'?\', \'O\')
I hadn't seen @MykhayloKopytonenko's solution when I went to write mine, so mine is similar:
tuples = [('Wanna', 'O'),
('be', 'O'),
('like', 'O'),
('Alexander', 'B'),
('Coughan', 'I'),
('?', 'O'),
('foo', 'B'),
('bar', 'I'),
('baz', 'B'),]
results = [(t0[0], t1[0]) for t0, t1 in zip(tuples[:-1], tuples[1:])
if t0[1] == 'B' and t1[1] == 'I']
for r in results:
print("%s %s" % r)
This outputs:
Alexander Coughan
foo bar
>>>
If you absolutely must have the result returned as a string, change the list comprehension to:
results = ["%s %s" % (t0, t1) for t0, t1 in zip(tuples[:-1], tuples[1:])
if t0[1] == 'B' and t1[1] == 'I']
This takes advantage of the fact that, based on your criteria, the last element of your list of tuples will never be returned as the first element of the result set. As a result, the zip
effectively steps you through (tuples[n], tuples[n + 1])
so that you can easily examine the values.