5.6Python之列表推导式

列表推导式(List comprehensions) 是一种简洁的语法,用于创建新的列表,并可以在创建过程中对元素进行转换、筛选或组合操作

列表推导式的一般形式为:

python 复制代码
new_list = [expression for item in iterable if condition]

其中:

  • expression 是要应用于每个元素的表达式或操作。
  • **item**是来自可迭代对象(如列表、元组或字符串)的每个元素。
  • **iterable**是可迭代对象,提供要遍历的元素。
  • **condition**是一个可选的条件,用于筛选出满足条件的元素。

以下是列表推导式的使用案例:

案例一,创建一个包含1到5的平方的列表:

python 复制代码
squares = [x**2 for x in range(1, 6)]
print(squares)  

# [1, 4, 9, 16, 25]

案例二,筛选出长度大于等于5的字符串:

python 复制代码
words = ["apple", "banana", "cherry", "date", "elderberry"]
filtered_words = [word for word in words if len(word) >= 5]
print(filtered_words)  

# ["apple", "banana", "cherry"]

案例三,将两个列表中的元素进行组合:

python 复制代码
numbers = [1, 2, 3]
letters = ['A', 'B', 'C']
combined = [(number, letter) for number in numbers for letter in letters]
print(combined)  

# [(1, 'A'), (1, 'B'), (1, 'C'), (2, 'A'), (2, 'B'), (2, 'C'), (3, 'A'), (3, 'B'), (3, 'C')]
相关推荐
weixin_459753942 小时前
golang如何实现Trace上下文传播_golang Trace上下文传播实现思路
jvm·数据库·python
zhangfeng11332 小时前
openclaw skills 小龙虾技能 通讯仿真 matlab skill Simulink Agentic Toolkit,通过kimi找到,mcp通讯
开发语言·matlab·openclaw·通讯仿真
weixin_444012932 小时前
PHP 中逻辑或(--)运算符的正确使用与条件逻辑重构指南
jvm·数据库·python
iAm_Ike8 小时前
Go 中自定义类型与基础类型间的显式类型转换详解
jvm·数据库·python
iuvtsrt8 小时前
Golang怎么实现方法集与接口的匹配_Golang如何理解值类型和指针类型实现接口的区别【详解】
jvm·数据库·python
chao1898448 小时前
基于 SPEA2 的多目标优化算法 MATLAB 实现
开发语言·算法·matlab
赏金术士9 小时前
Kotlin 习题集 · 高级篇
android·开发语言·kotlin
旦莫9 小时前
AI驱动的纯视觉自动化测试:知识库里应该积累什么知识内容
人工智能·python·测试开发·pytest·ai测试
楼兰公子10 小时前
buildroot 在编译rust时裁剪平台类型数量的方法
开发语言·后端·rust
知识领航员10 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github