python推导式

python推导式

本博客记录python的推导式

  1. 列表推导式
  2. 字典推导式

1. 列表推导式

列表推导式是 Python 中一种强大的工具,用于创建列表。它允许您使用简洁的语法从现有列表或其他可迭代对象中生成新的列表。

基本语法:

[<表达式> for <变量> in <可迭代对象> if <条件表达式>]

例子1:创建一个包含 1 到 10 的列表:

numbers = [x for x in range(1, 11)]
print(numbers)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

例子2:创建一个包含偶数的列表

even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)

[2, 4, 6, 8, 10]

例子3:创建一个包含字符串长度的列表

strings = ["hello", "world", "python"]
string_lengths = [len(s) for s in strings]
print(string_lengths)

[5, 5, 6]

例子4:创建一个包含嵌套列表的列表

nested_list = [[x for x in range(1, 4)] for y in range(3)]
print(nested_list)

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

例子5:使用条件表达式过滤元素

fruits = ["apple", "banana", "cherry", "orange", "mango"]
filtered_fruits = [fruit for fruit in fruits if fruit.startswith("a")]
print(filtered_fruits)

['apple']

2. 字典推导式

基本语法

[<>: <> for <>, <> in <可迭代对象> if <条件表达式>]
# or
{key: value for key, value in iterable if }

等同形式:

model_parameters = {
    input_info.name: input_info for input_info in onnx_model.graph.input
}

model_parameters = {}
for input_info in onnx_model.graph.input:
  	model_parameters[input_info.name] = input_info

例子1:创建一个包含 1 到 10 的数字字典

numbers = {x: x for x in range(1, 11)}
print(numbers)

#输出:
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}

例子2:创建一个包含偶数的字典

even_numbers = {x: x for x in range(1, 11) if x % 2 == 0}
print(even_numbers)

#输出:
{2: 2, 4: 4, 6: 6, 8: 8, 10: 10}

例子3:创建一个包含所有元音的字典

vowels = {l: l for l in "abcdefghijklmnopqrstuvwxyz" if l in "aeiou"}
print(vowels)

#输出:
{'a': 'a', 'e': 'e', 'i': 'i', 'o': 'o', 'u': 'u'}

例子4: 创建一个包含字符串长度映射的字典

strings = ["hello", "world", "python"]
string_lengths = {s: len(s) for s in strings}
print(string_lengths)

# 输出:
{'hello': 5, 'world': 5, 'python': 6}

例子5:键和值均需要遍历的情况

hybrid = [("apple", 10), ("banana", 20), ("cherry", 30), ("orange", 40), ("mango", 50)]
fruit_prices = {fruit: price for fruit, price in hybrid}
print(fruit_prices)

# 输出:
{'apple': 10, 'banana': 20, 'cherry': 30, 'orange': 40, 'mango': 50}

例子5:使用条件表达式过滤键值对

fruits = ["apple", "banana", "cherry", "orange", "mango"]
prices = [10, 20, 30, 40, 50]
fruit_prices = {fruit: price for fruit, price in zip(fruits, prices) if fruit.startswith("a")}
print(fruit_prices)

# 输出:
{'apple': 10}

你可能感兴趣的:(python)