
列表推导式:
列表推导式是一种简洁优雅的Python语法,允许在一行代码中创建或修改列表。
示例1:打印包含字母“a”的水果(使用for循环):
<code class="python">fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist) # 输出:['apple', 'banana', 'mango']</code>示例1(使用列表推导式):
<code class="python">fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) # 输出:['apple', 'banana', 'mango']</code>
示例2:计算给定数字的平方(使用for循环):
<code class="python">l = [10, 20, 30, 40]
newlist = []
for num in l:
newlist.append(num**2)
print(newlist) # 输出:[100, 400, 900, 1600]</code>示例2(使用列表推导式):
<code class="python">l = [10, 20, 30, 40] newlist = [num**2 for num in l] print(newlist) # 输出:[100, 400, 900, 1600]</code>
示例3:查找两个列表中相同的数字:
<code class="python">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]</code>示例4:查找两个列表中不同的数字:
<code class="python">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]</code>
示例5:笛卡尔积(使用列表推导式):
<code class="python">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)]</code>
示例6:字符串处理(使用列表推导式):
<code class="python">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</code>
示例7:字符串重复(使用循环):
<code class="python">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</code>示例8:矩阵扁平化(使用for循环):
<code class="python">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]</code>示例8(使用列表推导式):
<code class="python">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]</code>
示例9:列表元素条件转换(使用循环):
<code class="python">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']</code>示例10:矩阵行求和:
<code class="python">matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
for row in matrix:
print(sum(row), end=' ') # 输出:60 150 240</code>请注意,以上代码已修正了一些语法错误和逻辑错误,并添加了更清晰的注释。 列表推导式在很多情况下比传统的for循环更简洁高效。
以上就是日清单理解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号