本博客记录python的推导式
列表推导式是 Python 中一种强大的工具,用于创建列表。它允许您使用简洁的语法从现有列表或其他可迭代对象中生成新的列表。
基本语法:
[<表达式> for <变量> in <可迭代对象> if <条件表达式>]
numbers = [x for x in range(1, 11)]
print(numbers)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)
[2, 4, 6, 8, 10]
strings = ["hello", "world", "python"]
string_lengths = [len(s) for s in strings]
print(string_lengths)
[5, 5, 6]
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]]
fruits = ["apple", "banana", "cherry", "orange", "mango"]
filtered_fruits = [fruit for fruit in fruits if fruit.startswith("a")]
print(filtered_fruits)
['apple']
基本语法:
[<键>: <值> 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
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}
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}
vowels = {l: l for l in "abcdefghijklmnopqrstuvwxyz" if l in "aeiou"}
print(vowels)
#输出:
{'a': 'a', 'e': 'e', 'i': 'i', 'o': 'o', 'u': 'u'}
strings = ["hello", "world", "python"]
string_lengths = {s: len(s) for s in strings}
print(string_lengths)
# 输出:
{'hello': 5, 'world': 5, 'python': 6}
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}
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}