• 【Python】Python中一些有趣的用法


    Python是一种非常灵活和强大的编程语言,它有很多有趣的用法,以下是一些例子:

    1. 一行代码实现FizzBuzz

      print('\n'.join(['FizzBuzz'[i%3*4:i%5*8:-1] or str(i) for i in range(1, 101)]))
      
    2. 使用列表推导式生成斐波那契数列

      fib = [0, 1]
      [fib.append(fib[-2] + fib[-1]) for _ in range(10)]
      print(fib)
      
    3. 交换变量

      a, b = b, a
      
    4. 使用字符串的格式化方法打印图案

      print('\n'.join([''.join(['{:4}'.format(i*j) for i in range(1, 10)]) for j in range(1, 10)]))
      
    5. 递归计算阶乘

      def factorial(n):
          return 1 if n == 0 else n * factorial(n-1)
      print(factorial(5))
      
    6. 使用lambda表达式创建一个简单的计算器

      calc = {
          '+': lambda x, y: x + y,
          '-': lambda x, y: x - y,
          '*': lambda x, y: x * y,
          '/': lambda x, y: x / y
      }
      print(calc['*'](10, 2))
      
    7. 使用内置的dis模块查看字节码

      import dis
      dis.dis(lambda x: x**2)
      
    8. 使用reduce函数实现累加

      from functools import reduce
      print(reduce(lambda x, y: x + y, range(1, 101)))
      
    9. 利用字典实现switch-case结构

      def switch_case(case_value):
          return {
              'a': 'apple',
              'b': 'banana',
              'c': 'cherry'
          }.get(case_value, 'default')
      print(switch_case('b'))
      
    10. 生成器表达式

      squares = (x**2 for x in range(10))
      print(list(squares))
      
    11. 使用切片操作进行字符串反转

      original_string = "Hello, World!"
      reversed_string = original_string[::-1]
      print(reversed_string)
      
    12. 使用*操作符来解包列表

      list1 = [1, 2, 3]
      list2 = [4, 5, 6]
      combined_list = [*list1, *list2]
      print(combined_list)
      
    13. 使用map函数来应用函数到每个元素

      numbers = [1, 2, 3, 4, 5]
      squared = list(map(lambda x: x**2, numbers))
      print(squared)
      
    14. 使用filter函数来筛选元素

      numbers = range(10)
      even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
      print(even_numbers)
      
    15. 使用itertools模块进行迭代操作

      from itertools import chain, combinations
      def powerset(iterable):
          "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
          s = list(iterable)
          return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
      print(list(powerset([1, 2, 3])))
      
    16. 使用with语句管理资源

      with open('example.txt', 'r') as file:
          content = file.read()
      print(content)
      
    17. 使用装饰器添加函数功能

    
     def my_decorator(func):
         def wrapper():
             print("Something is happening before the function is called.")
             func()
             print("Something is happening after the function is called.")
         return wrapper
     @my_decorator
     def say_hello():
         print("Hello!")
     say_hello()
     
    
    1. 使用类装饰器记录函数调用次数

      class CallCounter:
          def __init__(self, func):
              self.func = func
              self.calls = 0
          def __call__(self, *args, **kwargs):
              self.calls += 1
              return self.func(*args, **kwargs)
      @CallCounter
      def say_hello():
          print("Hello!")
      say_hello()
      say_hello()
      print(say_hello.calls)  # Output will be 2
      
      
    2. 使用evalexec执行字符串中的代码

      code = "print('Hello from eval!')"
      eval(code)
      
      exec_code = """
      for i in range(3):
          print(f'Hello from exec {i}!')
      """
      exec(exec_code)
      
    3. 使用contextlib简化上下文管理器

      from contextlib import contextmanager
      @contextmanager
      def managed_resource(*args, **kwargs):
          # Set up the resource
          resource = acquire_resource(*args, **kwargs)
          try:
              yield resource
          finally:
              # Clean up the resource
              release_resource(resource)
      with managed_resource() as resource:
          # Use the resource
          pass
      

    以上这些例子展示了 Python 的许多有趣和强大的特性,如列表推导式、字典和集合的用法、lambda表达式、递归以及生成器、装饰器、上下文管理器、迭代器、生成器等,它们在编写高效和可读性强的代码时非常有用。这些特性使得 Python 在解决某些问题时显得格外简洁和高效。

  • 相关阅读:
    彻底读懂用户线程和守护线程(代码详解)
    求组合数的四种方式
    如何导出PPT画的图为高清图片?插入到world后不压缩图像的设置方法?
    LabVIEW用户界面设计
    4.MidBook项目经验之MonogoDB和easyExcel导入导出
    puttygen工具ppk文件版本配置
    Vue源码阅读【番外篇】:为什么Proxy需要搭配Reflect来实现响应式?
    网易Airtest全新推出:小型便携式集群解决方案!
    [附源码]JAVA毕业设计九宫格日志网站(系统+LW)
    Java案例找素数(三种方法)
  • 原文地址:https://blog.csdn.net/Young_Pro/article/details/141072786