当前位置 博文首页 > 程序员石磊:Python 10个优雅的写法,你会吗?

    程序员石磊:Python 10个优雅的写法,你会吗?

    作者:[db:作者] 时间:2021-08-08 10:13

    优雅的代码读起来像诗一样美。talk is cheap,show me the code!

    pexels-pixabay-237272.jpg

    1. 一行代码实现2个变量值交换

    你能想出一种不用第三个变量就能交换两个变量的方法吗?请看:

    a = 1
    b = 2
    a, b = b, a
    

    2. 不用循环实现重复字符串

    name = "程序员石磊"
    print(name * 4)
    

    输出:

    程序员石磊程序员石磊程序员石磊程序员石磊
    

    3. 字符转置

    sentence = "程序员石磊"
    reversed = sentence[::-1]
    print(reversed)
    

    输出:

    磊石员序程
    

    4. 将字符串列表压缩为一个字符串

    words = ["程", "序", "员", "石", "磊"]
    combined = " ".join(words)
    print(combined)
    

    输出:

    程 序 员 石 磊
    

    5. 比较

    您可以将比较组合在一起,而不是将代码分成两个或多个部分。这就像你写数学一样。例如:

    x = 100
    res = 0 < x < 1000
    print(res)
    

    输出:

    True
    

    6. 查找列表中出现次数最多的元素

    test = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]
    most_frequent = max(set(test), key = test.count)
    print(most_frequent)
    

    输出:

    2
    

    7. 列表元素分散到变量

    您可以将元素列表解分散为变量。只需保持变量的数量与列表元素的数量相同。

    arr = [1, 2, 3]
    a,b,c = arr
    print(a, b, c)
    

    输出:

    1 2 3
    

    8. 单行If-Else语句

    在Python中,单行if-else语句称为条件运算符。例如:

    age = 30
    age_group = "Adult" if age > 18 else "Child"
    print(age_group)
    

    输出:

    Adult
    

    以下是使用条件运算符的模式:

    true_expression if condition else false_expression
    

    9. 用一行代码循环遍历列表

    您可以使用推导式来使用一行代码遍历列表。例如,让我们将列表中的每个数字都取二次方:

    numbers = [1, 2, 3, 4, 5]
    squared_numbers = [num * num for num in numbers]
    print(squared_numbers)
    

    输出:

    [1, 4, 9, 16, 25]
    

    注意:不仅仅局限于使用列表。您也可以以类似的单行方式对字典、集合和生成器使用推导式。

    dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    squared_dict = {key: num * num for (key, num) in dict1.items()}
    print(squared_dict)
    

    输出:

    {'a': 1, 'b': 4, 'c': 9, 'd': 16}
    

    10. 简化if表达式

    糟糕的写法

    if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:
    

    你也可以这么简写

    if n in [0, 1, 2, 3, 4, 5]
    

    最后感谢阅读!爱你们!

    cs