如何在Python中优雅地使用列表推导式?
在Python中,列表推导式是一种简洁的语法来生成新的列表。以下是一些使用列表推导式的优雅示例:
判断元素是否满足条件:
numbers = [1, 2, 3, 4, 5]
even_numbers = [n for n in numbers if n % 2 == 0]
对列表进行某种操作(如计算、排序等):
words = ['apple', 'banana', 'cherry']
unique_words = list(set(words))
sorted_words = sorted(words, key=len)
使用函数作为推导式的一部分:
numbers = [1, 2, 3, 4, 5]
even_and_squared = [(n, n**2)) for n in numbers if n % 2 == 0]
总之,列表推导式在Python中是一种优雅、简洁的语法来生成新的列表。
还没有评论,来说两句吧...