Files
python3-cookbook/cookbook/c01/p19_trans_reduce.py
2014-09-03 14:04:10 +08:00

40 lines
991 B
Python

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 转换并聚集函数
Desc :
"""
import os
def trans_reduce():
nums = [1, 2, 3, 4, 5]
s = sum(x * x for x in nums)
print(s)
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)
# 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'])
if __name__ == '__main__':
trans_reduce()