日清单理解
列表推导式:
列表推导式是一种简洁优雅的Python语法,允许在一行代码中创建或修改列表。
示例1:打印包含字母“a”的水果(使用for循环):
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]newlist = []for x in fruits: if "a" in x: newlist.append(x)print(newlist) # 输出:['apple', 'banana', 'mango']
示例1(使用列表推导式):
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]newlist = [x for x in fruits if "a" in x]print(newlist) # 输出:['apple', 'banana', 'mango']
示例2:计算给定数字的平方(使用for循环):
l = [10, 20, 30, 40]newlist = []for num in l: newlist.append(num**2)print(newlist) # 输出:[100, 400, 900, 1600]
示例2(使用列表推导式):
l = [10, 20, 30, 40]newlist = [num**2 for num in l]print(newlist) # 输出:[100, 400, 900, 1600]
示例3:查找两个列表中相同的数字:
l1 = [10, 20, 30, 40]l2 = [30, 40, 50, 60]# 使用for循环common_numbers = []for num in l1: if num in l2: common_numbers.append(num)print(common_numbers) # 输出:[30, 40]# 使用列表推导式common_numbers = [num for num in l1 if num in l2]print(common_numbers) # 输出:[30, 40]
示例4:查找两个列表中不同的数字:
l1 = [10, 20, 30, 40]l2 = [30, 40, 50, 60]different_numbers = [num for num in l1 if num not in l2] + [num for num in l2 if num not in l1]print(different_numbers) # 输出:[10, 20, 50, 60]
示例5:笛卡尔积(使用列表推导式):
l1 = [1, 2, 3]l2 = [5, 6, 7]output = [(i, j) for i in l1 for j in l2]print(output) # 输出:[(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)]
示例6:字符串处理(使用列表推导式):
s = "a1b2c3"letters = "".join([i for i in s if i.isalpha()])numbers = "".join([i for i in s if i.isdigit()])print(letters + numbers) # 输出:abc123
示例7:字符串重复(使用循环):
s = "a4k3b2"result = ""i = 0while i < len(s): char = s[i] count = int(s[i+1]) result += char * count i += 2print(result) # 输出:aaaaakkkbb
示例8:矩阵扁平化(使用for循环):
matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]output = []for row in matrix: for num in row: output.append(num)print(output) # 输出:[10, 20, 30, 40, 50, 60, 70, 80, 90]
示例8(使用列表推导式):
matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]output = [num for row in matrix for num in row]print(output) # 输出:[10, 20, 30, 40, 50, 60, 70, 80, 90]
示例9:列表元素条件转换(使用循环):
l = ['abc', 'def', 'ghi', 'jkl']output = []for i, alpha in enumerate(l): if i % 2 != 0: output.append(alpha.lower()) else: output.append(alpha)print(output) # 输出:['abc', 'def', 'ghi', 'jkl']
示例10:矩阵行求和:
matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]for row in matrix: print(sum(row), end=' ') # 输出:60 150 240
请注意,以上代码已修正了一些语法错误和逻辑错误,并添加了更清晰的注释。 列表推导式在很多情况下比传统的for循环更简洁高效。