Python列表推导式语法详解

这是 Python 中的列表推导式,是一种简洁高效的语法。让我为你详细解释:

基本语法

[expression for item in iterable if condition]

对应你代码的解释

# 传统写法
emmc_resource = []
for core in cores:
    if core in emmc_key:
        emmc_resource.append(core)

# 列表推导式写法(你代码中的写法)
emmc_resource = [core for core in cores if core in emmc_key]

更详细的例子

# 示例数据
cores = ['core1', 'core2', 'core3', 'core4']
emmc_key = ['core2', 'core4']
images_key = ['core1', 'core3']

# 你的代码
emmc_resource = [core for core in cores if core in emmc_key]
image_resource = [core for core in cores if core in images_key]

print(emmc_resource)   # 输出: ['core2', 'core4']
print(image_resource)  # 输出: ['core1', 'core3']

列表推导式的其他用法

# 1. 简单的转换
numbers = [1, 2, 3, 4]
squares = [x**2 for x in numbers]  # [1, 4, 9, 16]

# 2. 带条件的转换
even_squares = [x**2 for x in numbers if x % 2 == 0]  # [4, 16]

# 3. 多重循环
pairs = [(x, y) for x in [1,2] for y in [3,4]]  # [(1,3), (1,4), (2,3), (2,4)]

优点

  • 简洁:一行代码完成循环+条件判断
  • 可读性:逻辑清晰(一旦熟悉)
  • 性能:通常比普通循环稍快

列表推导式是 Python 的特色语法,用熟练后会觉得非常方便!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值