[Tutor] joining selected items in list
Steven D'Aprano
steve at pearwood.info
Mon Jun 25 02:23:14 CEST 2012
David wrote:
> Dear Tutors,
>
> I have a list that I wish to reorganise into fewer list items.
> What happens is that some of the items belong together:
> not ['keine', 'Antwort'] but ['Keine Antwort'].
>
> I am not aware of any list methods that can help me here, and would thus
> be grateful for a hint or two.
This solves like a good case for one of the oldest, most general techniques in
use: an accumulator.
You construct a new list, from the old list, but using a temporary accumulator
first. The basic idea is:
for each item in old list:
if data in the accumulator is complete:
move the completed accumulator data to the new list
clear the accumulator so it is ready to start collecting fresh data
otherwise:
move item from old list to the accumulator
There's a million variations on this, depending on whether you test the
accumulator data at the start of the loop or the end of the loop, how and
where you process items, etc.
In your case, it sounds like it will be even easier, since you need collect
*at most* two items:
set a temporary variable to empty # the accumulator
for each item in old list:
if the temporary variable is not empty:
combine the temp variable and the current item
move them to the new list
otherwise:
if item is complete on its own:
move it straight into the new list
otherwise:
move it to a temporary variable
Converting this to Python is trivial:
tmp = ''
for item in old_list:
if tmp:
new_list.append(tmp + item)
else:
if stands_alone(item): # You must write this function.
new_list.append(item)
else:
tmp = item
Define this function first:
def stands_alone(item):
decide whether item stands alone, and if so, return True
otherwise return False
That decision function is the hard part. Is there some rule that tells you
whether or not a word in the list belongs with the next word?
--
Steven
More information about the Tutor
mailing list