【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 在解决某些问题时显得格外简洁和高效。

  • 16
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值