【Python 学习笔记】list comprehension with if

how to do list comprehension with if?

List comprehension with an if condition in Python allows you to create a new list by iterating over an existing iterable and including only the elements that satisfy a specific condition. 

Example 1: Simple List Comprehension with if

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension with if condition to select even numbers
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Example 2: List Comprehension with if and else

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension with if-else to classify numbers as 'Even' or 'Odd'
classified_numbers = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]

print(classified_numbers)  # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

Example 3: Nested List Comprehension with if

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Flatten the matrix and select only the elements greater than 4
flattened_and_filtered = [num for row in matrix for num in row if num > 4]

print(flattened_and_filtered)  # Output: [5, 6, 7, 8, 9]

Summary:

  • With if only: [expression for item in iterable if condition]
  • With if and else: [expression_if_true if condition else expression_if_false for item in iterable]
  • Nested with if: [expression for sublist in outer_list for item in sublist if condition]

This concise and readable syntax is a powerful feature in Python for transforming and filtering lists in a single line.

"Answer Generated by OpenAI's ChatGPT"

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值