您的位置:首页 > 娱乐 > 明星 > 【Python】Python中一些有趣的用法

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

2024/10/6 14:35:30 来源:https://blog.csdn.net/Young_Pro/article/details/141072786  浏览:    关键词:【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_decoratordef say_hello():print("Hello!")say_hello()
  1. 使用类装饰器记录函数调用次数

    class CallCounter:def __init__(self, func):self.func = funcself.calls = 0def __call__(self, *args, **kwargs):self.calls += 1return 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 resourceresource = acquire_resource(*args, **kwargs)try:yield resourcefinally:# Clean up the resourcerelease_resource(resource)
    with managed_resource() as resource:# Use the resourcepass
    

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com