newbie q

Steve Holden steve at holdenweb.com
Thu Jan 13 15:16:40 CET 2005


Egor Bolonev wrote:

> 
> "Stephen Thorne" <stephen.thorne at gmail.com> сообщил/сообщила в новостях
> следующее: news:mailman.611.1105598828.22381.python-list at python.org...
> On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev <ebolonev at mail.ru> wrote:
> 
>> how to get rid of 'for' operator in the code?
>>
>> import os, os.path
>>
>> def _test():
>>     src = 'C:\\Documents and Settings\\Егор\\My Documents\\My Music\\'
>>
>>     for i in [x for x in os.listdir(src) if
>> os.path.isfile(os.path.join(src,
>> x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']:
>>         os.remove(os.path.join(src, i))
>>
>> if __name__ == '__main__':
>>     _test()
> 
> 
> import glob
> for x in glob.glob("*.m3u"):
>    os.remove(x)
> 
> i want to wipe out 'for x in []: f(x)' using map, lambda, reduce, filter 
> and List
> Comprehensions [x for x in []]
> just don't get how to add string to all elements of list
> 

Any statement of the form

     for i in [x for x in something]:

can be rewritten as

     for i in something:

Note that this doesn't mean you never want to iterate over a list 
comprehension. It's the easiest way, for example, to iterate over the 
first item of each list in a list of lists:

     for i in [x[0] for x in something]:

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119




More information about the Python-list mailing list