列表推导式:
列表推导式是一种简洁优雅的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 = 0 while i < len(s): char = s[i] count = int(s[i+1]) result += char * count i += 2 print(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循环更简洁高效。
以上就是日清单理解的详细内容,更多请关注php中文网其它相关文章!