python列表生成式学习

发布于:2024-05-10 ⋅ 阅读:(25) ⋅ 点赞:(0)

Python中的列表生成式(List Comprehensions)是一种简洁而强大的语法结构,用于快速创建列表。它允许您通过在一行代码中使用简洁的语法来生成列表,通常用于将一个可迭代对象(例如列表、元组、集合、字典等)转换为另一个列表。

列表生成式的一般语法结构为:

[expression for item in iterable if condition]

其中:

  • expression:是对item的操作或计算结果,用于生成新的列表元素。
  • item:是可迭代对象中的每个元素。
  • iterable:是一个可迭代对象,例如列表、元组、集合等。
  • if condition(可选):是一个条件表达式,用于过滤输入的元素,只有满足条件的元素才会被包含在生成的列表中。

下面是一些示例说明列表生成式的用法:

  1. 基本用法:将一个列表中的每个元素平方,并生成一个新的列表。
nums = [1, 2, 3, 4, 5]
squared_nums = [x ** 2 for x in nums]
print(squared_nums)  # Output: [1, 4, 9, 16, 25]
  1. 带有条件的列表生成式:只保留偶数,并将其平方。
nums = [1, 2, 3, 4, 5]
squared_even_nums = [x ** 2 for x in nums if x % 2 == 0]
print(squared_even_nums)  # Output: [4, 16]
  1. 使用内置函数:将字符串列表中的每个字符串转换为大写。
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words)  # Output: ['HELLO', 'WORLD', 'PYTHON']
  1. 嵌套列表生成式:生成一个二维数组。
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_matrix = [num for row in matrix for num in row]
print(flattened_matrix)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. 字典推导式:生成一个字典。
words = ["hello", "world", "python"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)  # Output: {'hello': 5, 'world': 5, 'python': 6}

通过使用列表生成式,可以简洁地表达复杂的逻辑,使代码更易读、更简洁。然而,在使用时,需要注意不要过度使用,以免影响代码的可读性。

test example

test = [i for i in range(1, 11)]
print(test)

test2 = [s.upper() for s in ['aa', 'bb', 'cc']]
print(test2)


test3 = [line for line in ['aa', "bbb", "ccc"] if len(line) > 2]
print(test3)

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

objects = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}]
a_list = [obj['a'] for obj in objects if obj['a'] > 2]
print(a_list)


result
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
['AA', 'BB', 'CC']
['bbb', 'ccc']
[2, 4, 6, 8, 10]
[3, 5]


网站公告

今日签到

点亮在社区的每一天
去签到