登录
首页 >  文章 >  python教程

日清单理解

时间:2025-01-10 21:14:59 151浏览 收藏

大家好,我们又见面了啊~本文《日清单理解》的内容中将会涉及到等等。如果你正在学习文章相关知识,欢迎关注我,以后会给大家带来更多文章相关文章,希望我们能一起进步!下面就开始本文的正式内容~

日清单理解

列表推导式:

列表推导式是一种简洁优雅的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循环更简洁高效。

终于介绍完啦!小伙伴们,这篇关于《日清单理解》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>