以下是一个示例代码,演示了如何按照条件创建子列表并执行操作:
# 定义一个判断条件的函数
def is_even(num):
return num % 2 == 0
# 定义一个操作函数
def square(num):
return num ** 2
# 原始列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 按照条件创建子列表并执行操作
even_numbers = [num for num in numbers if is_even(num)]
squared_numbers = [square(num) for num in numbers]
# 输出结果
print("原始列表:", numbers)
print("偶数列表:", even_numbers)
print("平方列表:", squared_numbers)
运行结果:
原始列表: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
偶数列表: [2, 4, 6, 8, 10]
平方列表: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
在上面的示例中,我们首先定义了一个判断条件的函数is_even
,用于判断一个数字是否为偶数。然后定义了一个操作函数square
,用于计算一个数字的平方。接下来,我们定义了一个原始列表numbers
,其中包含了一组数字。
然后,我们使用列表推导式按照条件is_even
创建了一个偶数列表even_numbers
,其中只包含原始列表中的偶数。同时,我们使用列表推导式使用操作函数square
计算了原始列表中每个数字的平方,创建了一个平方列表squared_numbers
。
最后,我们打印了原始列表、偶数列表和平方列表的内容。