• Python魔法:20个让你编程事半功倍的奇淫技巧(建议收藏)


    Python作为一门灵活、充满技巧的语言,有着很多奇技淫巧,今天小编就跟大家分享一下在平时工作中所积累的技巧,这里面既有语法上的技巧,也有库函数的应用,可以帮助大家在平时的工作中提升效率,规避某些错误,一起来看看吧。

    1. 列表推导式
    2. 字典推导式
    3. 使用 zip 进行并行迭代
    4. 使用 enumerate 获取迭代器索引和值
    5. 使用 collections.Counter 进行计数
    6. 使用 map 函数进行批量操作
    7. 使用列表解析展平列表
    8. 列表内容转字符串
    9. 去除列表中重复元素
    10. 将字典值作为参数传递
    11. 两个变量值互换
    12. 连续赋值
    13. 链式比较
    14. 重复列表
    15. 重复字符串
    16. 三目运算
    17. 字典合并
    18. 字符串反转
    19. 列表转字符串
    20. for else 语句

    1、列表推导式

    使用一行代码生成列表,提高代码的简洁性和可读性。

    squared = [x**2 for x in range(10)]
    print(squared)
    

    结果
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    当我们使用列表推导式 [x**2 for x in range(10)] 时,它等价于使用普通的 for 循环来生成一个列表。让我们将列表推导式转换为等效的普通 for 循环代码

    squared = []  # 创建一个空列表,用于存放计算结果
    
    for x in range(10):  # 对于范围内的每一个数 x
        squared.append(x**2)  # 计算 x 的平方并将结果添加到列表 squared 中
    
    print(squared)  # 打印最终的列表 squared
    

    2、字典推导式

    类似列表推导式,用于创建字典。所以代码用大括号包裹

    square_dict = {x: x**2 for x in range(5)}
    print(square_dict)
    

    结果
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

    3、使用 zip 进行并行迭代

    将多个可迭代对象压缩在一起进行并行迭代。

    names = ['Alice', 'Bob', 'Charlie']
    ages = [30, 35, 40]
    
    for name, age in zip(names, ages):
        print(name, age)
    

    结果
    Alice 30
    Bob 35
    Charlie 40

    4、使用 enumerate 获取迭代器索引和值

    在迭代时获取索引和对应的值,在迭代一些可迭代对象时(例如list,dict),可通过内置enumerate来获取迭代元素的索引值

    for index, value in enumerate(names):
        print(index, value)
    

    5、使用 collections.Counter 进行计数

    方便地计算可迭代对象中元素的频率。

    from collections import Counter
    
    words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
    word_counts = Counter(words)
    print(word_counts)
    

    结果
    Counter({'apple': 3, 'banana': 2, 'orange': 1})

    6、使用 map 函数进行批量操作

    通过map函数可进行批量操作,将函数应用于迭代器中的每个元素。

    nums = [1, 2, 3, 4, 5]
    
    def square(x):
        return x**2
    # 代码表示将list的每个元素迭代后应用square函数中
    squared_nums = list(map(square, nums))
    print(squared_nums)
    

    结果
    [1, 4, 9, 16, 25]

    7、使用列表解析展平列表

    将嵌套的列表展平为一维列表。

    nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
    flattened_list = [num for sublist in nested_list for num in sublist]
    print(flattened_list)
    

    结果
    [1, 2, 3, 4, 5, 6, 7, 8]

    还有一种方式可以连接两个列表

      
    a = [1, 2, 3]  
    b = [5, 6, 7]  
      
    c = [*a, *b]  
    print(c)
    

    结果
    [1, 2, 3, 5, 6, 7]

    8、列表内容转字符串

    而列表中会存在字符串、数字等类型的数据,通过map将列表中元素转换成str类型,然后通过join函数就可以完成列表到字符串的转换。

    9、去除列表中重复元素

    list1 = [1,2,3,4,5,2,1,4,2,1]  
    print(list(set(list1)))
    

    结果
    [1, 2, 3, 4, 5]

    10、将字典值作为参数传递

    当你想将一个字典的值作为参数传递给函数时,你可以使用 ** 运算符来解包字典并将其作为关键字参数传递给函数。以下是一个示例:

    def greet(name, age):  
        print(f"Hello, {name}! You are {age} years old.")  
      
    person_info = {'name': 'Alice', 'age': 30}  
      
    greet(**person_info)
    

    结果
    Hello, Alice! You are 30 years old.

    11、两个变量值互换

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

    12、连续赋值

    a = b = c = 50
    

    13、链式比较

    a = 15
    if (10 < a < 20):
        print("Hi")
    

    等价于

    a = 15
    if (a>10 and a<20):
        print("Hi")
    

    14、重复列表

    >>> [5,2]*4
    [5, 2, 5, 2, 5, 2, 5, 2]
    

    15、重复字符串

    >>> "hello"*3
    'hellohellohello'
    

    16、三目运算

    age = 30
    slogon = "牛逼" if  age == 30 else "niubility"
    

    等价于

    if age == 30:
        slogon = "牛逼"
    else:
        slogon = "niubility"
    

    17、字典合并

    >>> a= {"a":1}
    >>> b= {"b":2}
    >>> {**a, **b}
    {'a': 1, 'b': 2}
    >>>
    

    18、字符串反转

    >>> s = "i love python"
    >>> s[::-1]
    'nohtyp evol i'
    >>>
    

    19、列表转字符串

    >>> s = ["i", "love", "pyton"]
    >>> " ".join(s)
    'i love pyton'
    >>>
    

    20、for else 语句

    检查列表foo是否有0,有就提前结束查找,没有就是打印“未发现"

    found = False
    for i in foo: 
    	if i == 0: 
    		found = True
    		break 
    if not found: 
    	print("未发现")
    

    总结

    以上就是小编为大家分享总结的Python技巧,大家还有什么Python的奇淫技巧呢,欢迎转载、收藏、有所收获点赞支持一下。

    关注公众号【Python魔法师】,一起进群沟通学习~

    qrcode.jpg

  • 相关阅读:
    Java用poi实现读取Excel文件内容
    调用 sap.ui.base.ManagedObject 的构造函数时,如何传递绑定路径进去
    【phpMyadmin】MYSQL突破secure_file_priv写shell提权
    【网络层】RIP协议详解(应用层)、慢收敛、OSPF协议(适合大网络)
    ubuntu18/20 下如何生成core文件
    如何选择向量数据库|Weaviate Cloud v.s. Zilliz Cloud
    全新升级的AOP框架Dora.Interception[1]: 编程体验
    Python教程:快速入门-函数、函数参数及三元运算符
    基于阿里云服务实现短信验证码功能
    Shell编程之免交互
  • 原文地址:https://www.cnblogs.com/meet/p/18060315