• 【速度收藏】17条好用的Python技巧分享(含源代码)


    一、前言

    在这篇文章中,我将会总结最常用的Python技巧。大多数这些技巧都是我在写Python作业时使用过的简单的trick,这里分享给大家。

    总结不易,还望各位看官大大收藏点赞!

    二、技巧总结

    1. 处理用户的多个输入

    有时我们需要从用户那里获得多个输入,以便使用循环或任何迭代,一般的写法如下:

    n1 = input("请输入第一个: ")
    n2 = input("请输入第二个: ")
    n3 = input("请输入第三个: ")
    print(n1, n2, n3)
    
    • 1
    • 2
    • 3
    • 4

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    请输入第一个: 1
    请输入第二个: 2
    请输入第三个: 3
    1 2 3
    
    • 1
    • 2
    • 3
    • 4
    • 5

    但是更好的处理方法如下:

    n1, n2, n3 = input("请输入: ").split()
    print(n1, n2, n3)
    
    • 1
    • 2

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    请输入: 1 2 3
    1 2 3
    
    • 1
    • 2
    • 3

    split()函数里面可以填写输入的分割类型,比如:

    n1, n2, n3 = input("请输入: ").split(',')
    print(n1, n2, n3)
    
    • 1
    • 2

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    请输入: 1,2,3
    1 2 3
    
    • 1
    • 2
    • 3

    2. 处理多个条件语句

    如果我们在代码中需要检查多个条件语句,此时我们可以使用 all()any() 函数来实现我们的目标。

    一般来说,有下面两种情况:

    1. 当我们有多个 and 条件时使用 all()

    2. 当我们有多个 or 条件时使用 any()

    这种用法将使我们的代码更加清晰易读,可以方便我们在调试时不会遇到麻烦。

    (1)all的用法

    对于all()的一般例子如下:

    size = "xl"
    color = "blue"
    price = 50
    if size == "xl" and color == "blue" and price < 100:
        print("Yes, I want to but the product.")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    更好的处理方法如下:

    conditions = [
        size == "xl",
        color == "blue",
        price < 100,
    ]
    if all(conditions):
        print("Yes, I want to but the product.")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    (2)any的用法

    对于any()的一般例子如下:

    size = "lg"
    color = "blue"
    price = 50
    if size == "lg" or color == "blue" or price < 100:
        print("Yes, I want to but the product.")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    更好的处理方法如下:

    conditions = [
        size == "lg",
        color == "blue",
        price < 100,
    ]
    if any(conditions):
        print("Yes, I want to but the product.")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3. 判断数字奇偶性

    这很容易实现,我们从用户那里得到输入,将其转换为整数,检查对数字2的求余操作,如果余数为零,则它是偶数。

    print('odd' if int(input('Enter a number: ')) % 2 else 'even')
    
    • 1

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    Enter a number: 10
    even
    
    • 1
    • 2
    • 3

    4. 交换变量

    在Python中如果需要交换变量的值,我们无需定义临时变量来操作。这个题相信对于大家没有什么问题,但是学过其他编程语言的同学可能会有影响。

    我们一般使用如下代码来实现变量交换:

    v1 = 100
    v2 = 200
    temp = v1
    v1 = v2
    v2 = temp
    
    • 1
    • 2
    • 3
    • 4
    • 5

    但是更好的处理方法如下:

    v1 = 100
    v2 = 200
    v1, v2 = v2, v1
    
    • 1
    • 2
    • 3

    5. 反转字符串

    将字符串进行反转最简单的实现方式为 [::-1] ,代码如下:

    print("I love Python"[::-1])
    
    • 1

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    nohtyP evol I
    
    • 1
    • 2

    6. 判断一个字符串是否为回文串

    在Python中判断一个字符串是否为回文串,只需要使用语句:

    string.find(string[::-1])== 0 
    
    • 1

    示例代码如下:

    v1 = "madam" # 是回文串
    v2 = "master" # 不是回文串
    print(v1.find(v1[::-1]) == 0) # True
    print(v1.find(v2[::-1]) == 0) # False
    
    • 1
    • 2
    • 3
    • 4

    7. 尽量使用 Inline if statement

    大多数情况下,我们在条件之后只有一个语句,因此使用Inline if statement 可以帮助我们编写更简洁的代码。举例如下,一般的写法为:

    name = "ali"
    age = 22
    if name:
        print(name)
    if name and age > 18:
        print("user is verified")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    ali
    user is verified
    
    • 1
    • 2
    • 3

    但是更好的处理方法如下:

    # a better approach
    print(name if name else "")
    """ here you have to define the else condition too"""
    name and print(name)
    age > 18 and name and print("user is verified")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    8. 删除list中的重复元素

    我们不需要遍历整个list列表来检查重复元素,我们可以简单地使用 set() 来删除重复元素,代码如下:

    lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
    print(lst)
    unique_lst = list(set(lst))
    print(unique_lst)
    
    • 1
    • 2
    • 3
    • 4

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
    [0, 1, 2, 3, 4, 5, 6, 7, 9]
    
    • 1
    • 2
    • 3

    9. 找到list中重复最多的元素

    在Python中可以使用 max( ) 函数并传递 list.count 作为key,即可找出列表list中重复次数最多的元素,代码如下:

    lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0]
    most_repeated_item = max(lst, key=lst.count)
    print(most_repeated_item)
    
    • 1
    • 2
    • 3

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    4
    
    • 1
    • 2

    10. list 生成式

    Python中我最喜欢的功能就是list comprehensions , 这个特性可以使我们编写非常简洁功能强大的代码,而且这些代码读起来几乎像自然语言一样通俗易懂。举例如下:

    numbers = [1,2,3,4,5,6,7]
    evens = [x for x in numbers if x % 2 == 0]
    odds = [y for y in numbers if y not in evens]
    print(evens)
    print(odds)
    cities = ['London', 'Dublin', 'Oslo']
    def visit(city):
        print("Welcome to "+city)
    for city in cities:
        visit(city)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    [2, 4, 6]
    [1, 3, 5, 7]
    Welcome to London
    Welcome to Dublin
    Welcome to Oslo
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    11. 使用*args传递多个参数

    在Python中我们可以使用*args来向函数传递多个参数,举例如下:

    def sum_of_squares(n1, n2):
        return n1**2 + n2**2
    print(sum_of_squares(2,3))
    # output: 13
    """
    what ever if you want to pass, multiple args to the function 
    as n number of args. so let's make it dynamic.
    """ 
    def sum_of_squares(*args):
        return sum([item**2 for item in args])
    # now you can pass as many parameters as you want
    print(sum_of_squares(2, 3, 4))
    print(sum_of_squares(2, 3, 4, 5, 6))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    13
    29
    90
    
    • 1
    • 2
    • 3
    • 4

    12. 在循环时处理下标

    有时我们在工作中,想要获得循环中元素的下标,一般来说,比较优雅的写法如下:

    lst = ["blue", "lightblue", "pink", "orange", "red"]
    for idx, item in enumerate(lst):
         print(idx, item)
    
    • 1
    • 2
    • 3

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    0 blue
    1 lightblue
    2 pink
    3 orange
    4 red
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    13. 拼接list中多个元素

    在Python中一般使用Join() 函数来将list中所有元素拼接到一起,当然我们也可以在拼接的时候添加拼接符号,样例如下:

    names = ["john", "sara", "jim", "rock"]
    print(", ".join(names))
    
    • 1
    • 2

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    john, sara, jim, rock
    
    • 1
    • 2

    14. 将两个字典进行合并

    在Python中我们可以使用{**dict_name, **dict_name2, … }将多个字典进行合并,样例如下:

    d1 = {"v1": 22, "v2": 33}
    d2 = {"v2": 44, "v3": 55}
    d3 = {**d1, **d2}
    print(d3)
    
    • 1
    • 2
    • 3
    • 4

    结果如下:

    {'v1': 22, 'v2': 44, 'v3': 55}
    
    • 1

    15. 使用两个list生成一个字典

    在Python中,如果我们需要将两个列表中对应的元素组成字典,那么我们可以使用 zip 功能来方便地做到这一点。代码如下:

    keys = ['a', 'b', 'c']
    vals = [1, 2, 3]
    zipped = dict(zip(keys, vals))
    
    • 1
    • 2
    • 3

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    {'a': 1, 'b': 2, 'c': 3}
    
    • 1
    • 2

    16. 字典按照value进行排序

    在Python中我们使用sorted()函数来按照字典的value来对其进行排序.代码如下:

    d = {
        "v1": 80,
        "v2": 20,
        "v3": 40,
        "v4": 20,
        "v5": 10,
    }
    sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
    print(sorted_d)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    输出结果为:

    (base) D:\Code Project>D:/Anaconda/python.exe "d:/Code Project/24.研一周五六七节Python作业/demo.py"
    {'v5': 10, 'v2': 20, 'v4': 20, 'v3': 40, 'v1': 80}
    
    • 1
    • 2

    当然我们也可以使用itemgetter( )来替代上述 lambda函数,代码如下:

    from operator import itemgetter
    sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
    
    • 1
    • 2

    更进一步,我们也可以通过传递 reverse=True 对其进行降序排序:

    sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))
    
    • 1

    17. Pretty print

    在Python中使用Print()函数,有时候的输出贼拉拉丑陋,此时我们使用pprint可以使输出更加美观,样例如下:

    from pprint import pprint
    data = {
        "name": "john deo",
        "age": "22",
        "address": {"contry": "canada", "state": "an state of canada :)", "address": "street st.34 north 12"},
        "attr": {"verified": True, "emialaddress": True},
    }
    print(data)
    pprint(data)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    输出如下:

    {'name': 'john deo', 'age': '22', 'address': {'contry': 'canada', 'state': 'an state of canada :)', 'address': 'street st.34 north 12'}, 'attr': {'verified': True, 'emialaddress': True}}
    {'address': {'address': 'street st.34 north 12',
                 'contry': 'canada',
                 'state': 'an state of canada :)'},
     'age': '22',
     'attr': {'emialaddress': True, 'verified': True},
     'name': 'john deo'}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    可见使用pprint函数可以让字典的输出更加容易阅读。

  • 相关阅读:
    一文解读该用开源BI工具还是智能BI工具?
    基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现
    【App自动化测试】(十一)自动化关键数据记录
    尚医通 (二十七) --------- 排班接口开发
    BPA仿真软件需要购买吗,BPA电力仿真软件教程
    【重温Python基础】最全Python基础知识点,加班熬夜花了三天终于总结出来了,非常详细
    【面试题】为什么Object.prototype.toString.call() 可以准确判断对象类型?
    【设计模式】使用原型模式完成业务中“各种O”的转换
    14、顺时针打印矩阵
    javaee spring 声明式事务管理方式2 注解方式
  • 原文地址:https://blog.csdn.net/wzk4869/article/details/127766739