Python是一种非常灵活和强大的编程语言,它有很多有趣的用法,以下是一些例子:
-
一行代码实现FizzBuzz:
pythonprint('\n'.join(['FizzBuzz'[i%3*4:i%5*8:-1] or str(i) for i in range(1, 101)]))
-
使用列表推导式生成斐波那契数列:
pythonfib = [0, 1] [fib.append(fib[-2] + fib[-1]) for _ in range(10)] print(fib)
-
交换变量:
pythona, b = b, a
-
使用字符串的格式化方法打印图案:
pythonprint('\n'.join([''.join(['{:4}'.format(i*j) for i in range(1, 10)]) for j in range(1, 10)]))
-
递归计算阶乘:
pythondef factorial(n): return 1 if n == 0 else n * factorial(n-1) print(factorial(5))
-
使用lambda表达式创建一个简单的计算器:
pythoncalc = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y } print(calc['*'](10, 2))
-
使用内置的
dis
模块查看字节码:pythonimport dis dis.dis(lambda x: x**2)
-
使用
reduce
函数实现累加:pythonfrom functools import reduce print(reduce(lambda x, y: x + y, range(1, 101)))
-
利用字典实现switch-case结构:
pythondef switch_case(case_value): return { 'a': 'apple', 'b': 'banana', 'c': 'cherry' }.get(case_value, 'default') print(switch_case('b'))
-
生成器表达式:
pythonsquares = (x**2 for x in range(10)) print(list(squares))
-
使用切片操作进行字符串反转:
pythonoriginal_string = "Hello, World!" reversed_string = original_string[::-1] print(reversed_string)
-
使用
*
操作符来解包列表:pythonlist1 = [1, 2, 3] list2 = [4, 5, 6] combined_list = [*list1, *list2] print(combined_list)
-
使用
map
函数来应用函数到每个元素:pythonnumbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared)
-
使用
filter
函数来筛选元素:pythonnumbers = range(10) even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
-
使用
itertools
模块进行迭代操作:pythonfrom 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])))
-
使用
with
语句管理资源:pythonwith open('example.txt', 'r') as file: content = file.read() print(content)
-
使用装饰器添加函数功能:
python
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()
-
使用类装饰器记录函数调用次数:
pythonclass 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
-
使用
eval
和exec
执行字符串中的代码:pythoncode = "print('Hello from eval!')" eval(code) exec_code = """ for i in range(3): print(f'Hello from exec {i}!') """ exec(exec_code)
-
使用
contextlib
简化上下文管理器:pythonfrom 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 在解决某些问题时显得格外简洁和高效。