# 各种推导式详解

variable = [out_exp_res for out_exp in input_list if out_exp == 2]
out_exp_res:　　列表生成元素表达式，可以是有返回值的函数。
for out_exp in input_list：　　迭代input_list将out_exp传入out_exp_res表达式中。
if out_exp == 2：　　根据条件过滤哪些值可以。

multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print(multiples)

names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]

print([name for lst in names for name in lst if name.count('e') >= 2])  # 注意遍历顺序，这是实现的关键


mcase = {'a': 10, 'b': 34}
mcase_frequency = {mcase[k]: k for k in mcase}
print(mcase_frequency)

mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()}
print(mcase_frequency)

squared = {x**2 for x in [1, -1, 2]}
print(squared)
# Output: set([1, 4])

1.[name.upper() for name in names if len(name)>3]
2.[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
3. [row[2] for row in M] 
code

posted @ 2017-08-02 21:12  Eva_J  阅读(6634)  评论(0编辑  收藏  举报