diff --git a/comprehensions.html b/comprehensions.html index 79db3bf..03550bc 100644 --- a/comprehensions.html +++ b/comprehensions.html @@ -194,11 +194,11 @@ body{counter-reset:h1 3}
>>> a_list = [1, 9, 8, 4] ->>> [elem * 2 for elem in a_list] ① +>>> [elem * 2 for elem in a_list] ① [2, 18, 16, 8] ->>> a_list ② +>>> a_list ② [1, 9, 8, 4] ->>> a_list = [elem * 2 for elem in a_list] ③ +>>> a_list = [elem * 2 for elem in a_list] ③ >>> a_list [2, 18, 16, 8]
FIXME +
You can use any Python expression in a list comprehension, including the functions in the os module for manipulating files and directories.
->>> glob.glob('*.xml')
+>>> import os, glob
+>>> glob.glob('*.xml') ①
['feed-broken.xml', 'feed-ns0.xml', 'feed.xml']
->>> [os.path.abspath(filename) for filename in glob.glob('*.xml')]
+>>> [os.path.abspath(filename) for filename in glob.glob('*.xml')] ②
['c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-broken.xml',
'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-ns0.xml',
'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed.xml']
+List comprehensions can also filter items, producing a result that may be smaller than the original list. + +
+>>> import os, glob
+>>> [f for f in glob.glob('*.py') if os.stat(f).st_size > 6000] ①
+['pluraltest6.py',
+ 'romantest10.py',
+ 'romantest6.py',
+ 'romantest7.py',
+ 'romantest8.py',
+ 'romantest9.py']
+
+if clause at the end of the list comprehension. The expression after the if keyword will be evaluated for each item in the list. If the expression evaluates to True, the item will be included in the output. This list comprehension looks at the list of all .py files in the current directory, and the if expression filters that list by testing whether the size of each file is greater than 6000 bytes. There are six such files, so the list comprehension returns a list of six filenames.
+All the examples of list comprehensions so far have featured simple expressions — multiply a number by a constant, call a single function, or simply return the original list item (after filtering). But there’s no limit to how complex a list comprehension can be. + +
+>>> import os, glob
+>>> [(os.stat(f).st_size, os.path.abspath(f)) for f in glob.glob('*.xml')] ①
+[(3074, 'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-broken.xml'),
+ (3386, 'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed-ns0.xml'),
+ (3070, 'c:\\Users\\pilgrim\\diveintopython3\\examples\\feed.xml')]
+.xml files in the current working directory, gets the size of each file, and returns a tuple of the file size and the absolute path of each file.
+FIXME
>>> print("\n".join(["{0:>8} {1}".format(humansize.approximate_size(os.stat(f).st_size, False), os.path.abspath(f)) for f in glob.glob('*.py')]))