--- On Mon, 1/31/11, Wayne Werner <waynejwer...@gmail.com> wrote:
From: Wayne Werner <waynejwer...@gmail.com> Subject: Re: [Tutor] search list with regex To: "Elwin Estle" <chrysalis_reb...@yahoo.com> Cc: tutor@python.org Date: Monday, January 31, 2011, 10:20 AM On Mon, Jan 31, 2011 at 7:07 AM, Elwin Estle <chrysalis_reb...@yahoo.com> wrote: Tcl's list search command has the option to search for a list element that matches a given regex. Is there something similar in python? If not, it seems like it should be fairly trivial for me to write my own (just wondering if I would be re-inventing the wheel). matching_items = []for item in yourlist: result = re.search('[sS]ome expression', item) # and of course s/search/match, if you're interested in matching if result: matching_items.append(item) Or you could go for more terse syntax via list comp: matching_items = [item for item in yourlist if re.search('contains', item)] Or if you want one at a time you could change [] for () and turn it into a generator expression. However, the list itself doesn't have any method for matching. Here are its "public" methods: appendcountextendindexinsertpopremovereversesort HTH,Wayne ...here I am...dutifully bottom posting... That's kinda what I figured, and the code you posted is pretty much what I had in mind. The list I plan to use it with is pretty short, but varies in length (am parsing a file full of Vcards). One thing I notice, is that working with lists in Python is WAY faster than doing it in Tcl. I have occasion to parse various text files and my standard method is to slurp the whole thing up into a string variable, then break it up into a list that I can then work on with various string or regex commands.. In Tcl, I've had it take minutes to do this process, but it takes just seconds in Python.
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor