[Tutor] Iterating over a list for a certain character...

Gregor Lingl glingl@aon.at
Fri, 14 Dec 2001 00:28:04 +0100


----- Original Message -----
From: "Sean 'Shaleh' Perry" <shalehperry@attbi.com>
To: "Brett Kelly" <inkedmn@gmx.net>
Cc: <tutor@python.org>
Sent: Thursday, December 13, 2001 11:55 PM
Subject: Re: [Tutor] Iterating over a list for a certain character...


>
> On 13-Dec-2001 Brett Kelly wrote:
> > ok, i have read a file into a list of strings, and i need to copy out
all of
> > the strings that contain a certain character, sort them, and print them.
> >
> > how would i do that?
> >
>
> take a look at:
>
> >>> c = 's'
> >>> c in 'streets'
> 1

.. or try - somewhat more sophisticated:

>>> l = ['bim', 'bam', 'schrumm']
>>> filter(lambda x: 'i' in x, l)
['bim']
>>> filter(lambda x: 'b' in x, l)
['bim', 'bam']
>>> filter(lambda x: 'm' in x, l)
['bim', 'bam', 'schrumm']
>>>

so you can make up the following definition:

>>> def wordswith(char, lst):
...  return filter(lambda x, c = char : c in x, lst)
...
>>> wordswith('i',l)
['bim']
>>> wordswith('c',l)
['schrumm']
>>> wordswith('m',l)
['bim', 'bam', 'schrumm']
>>>


who knows a more elegant way?

Gregor