Kent Johnson wrote: > Marc Tompkins wrote: > >> I'm working with delimited files (ANSI X12 EDI nonsense, to be >> precise.) First I load the records to a list: >> tmpSegs = inString.split(self.SegTerm) >> >> Now, I want to replace each string in that list with a string: >> >> for seg in tmpSegs: # 'seg' is short for 'segment' >> seg = seg.split(self.ElemSep) >> >> It doesn't work. If I check the contents of tmpSegs, it's still a list >> of strings - not a list of lists. So I do this instead: >> tmpSegs2 = [] >> for seg in tmpSegs: >> tmpSegs2.append(seg.split(self.sElemSep)) >> del tmpSegs >> >> This works. And, for the size of files that I'm likely to run into, >> creating the extra list and burning the old one is probably not going to >> swamp the machine - but it feels clumsy to me, like if I just knew the >> secret I could be much more elegant about it. >> > > Creating a new list is fine, actually. You can do it more elegantly with > a list comprehension, and it's fine to assign to the same name, which > will implicitly delete the old list: > tmpSegs = [ seg.split(self.ElemSep) for seg in tmpSegs ] > > If you really want to replace elements in the same list you can use > enumerate to get indices: > > for i, seg in enumerate(tmpSegs): > tmpSegs[i] = seg.split(self.ElemSep) >
Very nice use of enumerate(), I like this better than my solution. Thanks, Kent. > or use slice assignment: > tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ] > > but I doubt those are needed in this case. > > >> What puzzles me most is that I can replace 'seg' with just about >> anything else - >> for seg in tmpSegs: >> seg = seg.strip() >> or >> for seg in tmpSegs: >> seg = 'bananas' >> or >> for seg in tmpSegs: >> seg = seg + ' bananas' >> and it works. So why can't I replace it with its own split? >> > > If by 'it works' you mean that tmpSegs is changed...you are mistaken or > there is something you are not showing. Can you show why you think this > changes tmpSegs? > > Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor