python字典推导式if-else && 列表推导式if-elseの拾遗

1、列表推导式(list comprehensions)

comprehensions --> 理解,故又称列表理解式,提供了一种简明扼要的方法[]来创建列表。它的结构是在一个中括号里包含一个表达式,然后是一个for语句,然后是0个或多个for或者if语句。那个表达式可以是任意的,意思是你可以在列表中放入任意类型的对象。返回结果将是一个新的列表,在这个以if和for语句为上下文的表达式运行完成之后产生。

1.1 一个 for 循环 推导

  • 基本格式
list_variable = [x for x in iterable] 
  • 示例用法
In [2]: list1 = [ x for x in range(1,11)]
   ...: print(list1)
   ...:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1.2 一个 for 循环 + 调用函数

推导式中可以调用 函数,这里 使用函数 int() 最后转化 int 类型 并 推导生成新的列表

In [11]: feet = ['12', '1024', '724', '996']

In [12]: feet = [int(x) for x in feet]

In [13]: print(feet)
[12, 1024, 724, 996]

1.3 一个 for 循环 + if 条件

正整数 1 到 10 之间,如果 能被 2 整除,则返回 此数字 的平方 输出列表

In [4]: new_list = [n**2 for n in range(1,11) if n%2==0]

In [5]: print(new_list)
[4, 16, 36, 64, 100]

1.4 一个 for 循环 + 多个 if 条件

正整数 0 到 99 之间,如果 能被 2 整除 同时 又能被 6 整除 ,则返回 生成 新列表

In [16]: divided = [x for x in range(100) if x % 2 == 0 if x % 6 == 0]

In [17]: print(divided)
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]

1.5 一个 for 循环 + if-else 条件

正整数 1 到 10 之间,如果数字 x 大于等于 7 则返回 x+1 ,否则 返回 x+5 ,返回生成新的列表

In [26]: new_list = [x+1 if x >= 7 else x+5 for x in range(1, 11)]

In [27]: print(new_list)
[6, 7, 8, 9, 10, 11, 8, 9, 10, 11]

1.6 多个 for 循环 + if 条件 推导

找到嵌套列表中名字含有两个‘e’的所有名字

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

In [41]: new_list = [name for elements in names for name in elements  if name.count('e') >= 2]

In [42]: print(new_list)
['Jefferson', 'Wesley', 'Steven', 'Jennifer']

1.7 嵌套列表推导 之 一个大列表内所有子列表推导生成新的大列表

嵌套列表中,大列表内包含 多个 子列表,通过列表推导生成式 输出所有元素生成到 新的 大列表内

In [33]: list_of_list = [[1,2,3],[4,5,6],[7,8]]

# Flatten `list_of_list`
In [34]: new_list = [y for x in list_of_list for y in x]

In [35]: print(new_list)
[1, 2, 3, 4, 5, 6, 7, 8]

1.8 嵌套列表推导 之 一个大列表内所有子列表推导生成新的子列表

矩阵 matrix 中 三个 小列表,现将 每个列元素 取出, 推导生成一个 新列表矩阵

In [48]: matrix = [[1,2,3],[4,5,6],[7,8,9]]

In [49]: new_list = [[row[i] for row in matrix] for i in range(3)]

In [50]: print(new_list)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

2、字典推导式

  • 基本格式
dict_variable = {key:value for (key, value) in iterable}  
dict_variable = {key:value for (key,value) in dictonary.items()}

2.1 字典的 value 变化 来 推导生成 新的 字典

  • 示例:使用字典推导式 让 每个 value 值 都乘以 2 ,从而 生成 新的字典
In [51]: dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

# Double each value in the dictionary
In [52]: double_dict1 = {k:v*2 for (k,v) in dict1.items()}

In [53]: print(double_dict1)
{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}

2.2 字典 的 key 变化 来 推导生成 新的字典

  • 示例:使用字典推导式 让 每个 key 值 都乘以 2 ,从而 生成 新的字典
In [59]: dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

In [60]: dict1_keys = {k*2:v for (k,v) in dict1.items()}

In [61]: print(dict1_keys)
{'aa': 1, 'bb': 2, 'cc': 3, 'dd': 4, 'ee': 5}

2.3 for 循环 + if 条件 推导生成 新 的字典

  • 普通方法使用 for循环 + if 实现 字典 k,v 键值对 添加
numbers = range(10)
new_dict_for = {}

# Add values to `new_dict` using for loop
for n in numbers:
    if n%2==0:
        new_dict_for[n] = n**2

print(new_dict_for)

输出:

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
  • 通过 推导式 一行 代码 搞定
In [65]: new_dict_for = {n:n**2 for n in range(10) if n%2 == 0 }

In [66]: print(new_dict_for)
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

2.4 原字典 for 循环 + if 条件 推导生成 新字典

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

# Check for items greater than 2
dict1_cond = {k:v for (k,v) in dict1.items() if v>2}

print(dict1_cond)

输出:

{'e': 5, 'c': 3, 'd': 4}

2.5 for 循环 + 两个 if 条件 推导生成字典

  • 两个 if 过滤 输出 键值对 生成新字典
In [70]: dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

In [71]: dict1_doubleCond = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0}

In [72]: print(dict1_doubleCond)
{'d': 4}

2.6 for 循环 + 三个 if 条件 推导生成字典

  • 三个 if 条件 即 多个 if 条件 过滤 输出推导 生成字典
In [73]: dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}

In [74]: dict1_tripleCond = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0 if v%3 == 0}

In [75]: print(dict1_tripleCond)
{'f': 6}

写成 普通 循环来看 如下:

dict1_tripleCond = {}

for (k,v) in dict1.items():
    if (v>=2 and v%2 == 0 and v%3 == 0):
            dict1_tripleCond[k] = v

print(dict1_tripleCond)

字典推导式 if-else

  • 示例:通过 if-else 条件 判断 奇偶数 改变 value 值,推导生成 新字典
In [76]: dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}

# Identify odd and even entries
In [77]: dict1_tripleCond = {k:('even' if v%2==0 else 'odd') for (k,v) in dict1.items()}

In [78]: print(dict1_tripleCond)
{'a': 'odd', 'b': 'even', 'c': 'odd', 'd': 'even', 'e': 'odd', 'f': 'even'}

嵌套字典 推导式

  • nested_dict 是具有以下键的字典:first 和 second,它们将字典对象保存在其值中。 该代码使用内部字典值并将其转换为float,然后将外部键与新的float内部值组合为新的字典。
In [81]: nested_dict = {'first':{'a':1}, 'second':{'b':2}}

In [82]: float_dict = {outer_k: {float(inner_v) for (inner_k, inner_v) in outer_v.items()} for (outer_k, outer_v) in nested_dict.items()}

In [83]: print(float_dict)
{'first': {1.0}, 'second': {2.0}}
  • 原循环推导生成如下
nested_dict = {'first':{'a':1}, 'second':{'b':2}}

for (outer_k, outer_v) in nested_dict.items():
    for (inner_k, inner_v) in outer_v.items():
        outer_v.update({inner_k: float(inner_v)})
nested_dict.update({outer_k:outer_v})

print(nested_dict)

输出:

{'first': {'a': 1.0}, 'second': {'b': 2.0}}

3、集合推导式

  • 示例:计算列表中每个值的平方,自带去重功能
In [85]: squared = {x**2 for x in [1 , -1, 2]}

In [86]: print(squared)
{1, 4}

你可能感兴趣的:(Python,python,列表推导式,字典推导式)