[Tutor] splits and pops
Kent Johnson
kent37 at tds.net
Sat Jul 12 16:56:27 CEST 2008
On Sat, Jul 12, 2008 at 8:55 AM, Eric Abrahamsen
<eric at ericabrahamsen.net> wrote:
> I've been fooling around with variations on the following (assuming
> splitlist = fullstring.split('\t')):
>
> for x in xrange(8, sys.maxint, 8):
> try:
> splitlist[x:x] = splitlist.pop(x).split('\n')
> except IndexError:
> break
>
> The first line correctly steps over all the list items that need to be
> split, but I can't come up with a line that correctly replaces those list
> items with the two strings I want. Either the cycle goes off and splits the
> wrong strings, or I get nested list items, which is not what I want. Can
> someone please point me in the right direction here?
The problem is that once you substitute a split field, the indices of
the remaining fields change so you are not looking at the right ones.
Some possibilities:
- work from the back of the list so the indices of the fields to be
processed don't change
- build a new list as you go
- keep track of an offset that you add to the index
The second one would be something like this (untested):
result = []
for i, value in enumerate(splitlist):
if (i+1) % 8 == 0:
result.extend(value.split('\n'))
else:
result.append(value)
Kent
More information about the Tutor
mailing list