Evaluated simultaneous switching sequence (filtered) data

Scene: reduced need to perform functions (e.g., sum (), min () , max ()), but first need to convert or filter data.

Generator expression usually used to filter data, sum, min, max parameters for iterable, and inheritance generator iterator, iterator inheritance iterable. It generates the same expressions as arguments to these functions.
The following example:

nums = [1, 2, 3, 4, 5]
s = sum(x * x for x in nums)

# Determine if any .py files exist in a directory
import os
files = os.listdir('dirname')
if any(name.endswith('.py') for name in files):
    print('There be python!')
else:
    print('Sorry, no python.')

# Output a tuple as CSV
s = ('ACME', 50, 123.45) 
print(','.join(str(x) for x in s))

# Data reduction across fields of a data structure
portfolio = [
    {'name':'GOOG', 'shares': 50},
    {'name':'YHOO', 'shares': 75},
    {'name':'AOL', 'shares': 20},
    {'name':'SCOX', 'shares': 65}
]
min_shares = min(s['shares'] for s in portfolio)
# Output 20

Using generators parameter is usually more effective and more elegant than first creating a temporary list. For example, if no generator expression, consider using this alternative implementations:

nums = [1, 2, 3, 4, 5]
s = sum([x * x for x in nums])

This is effective, but it introduces an extra step and create an additional list. For small list, it might not matter, but if nums large, will eventually create a large temporary data structures, can only be used once and discarded. Solutions iteratively generating the conversion data, and therefore a higher memory efficiency.
min (), max () and sorted () has an additional parameter key, the comparison can be customized. As follows:

# Original: Returns 20
min_shares = min(s['shares'] for s in portfolio)

# Alternative: Returns {'name': 'AOL', 'shares': 20}
min_shares = min(portfolio, key=lambda s: s['shares'])

Guess you like

Origin www.cnblogs.com/jeffrey-yang/p/11316549.html