Python 简洁且表达力强的语法通常可以让我们编写一行代码来执行各种任务,怎能让人不爱?
而同样的任务其它语言可能要敲很多行。
以下是一些例子,主要涉及到列表推导式、lambda 函数、切片和内置函数。
肯定不全,时不时的补充。
sum(i for i in range(1, 11) if i % 2 == 0)
squared = [x**2 for x in range(1, 6)]
odd_numbers = list(filter(lambda x: x % 2 != 0, range(1, 11)))
reversed_string = 'Hello, World!'[::-1]
pairs = list(zip([1, 2, 3], ['a', 'b', 'c']))
unique_elements = list(set([1, 2, 2, 3, 3, 4]))
from collections import Counter occurrences = Counter([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
flat_list = [item for sublist in [[1, 2], [3, 4], [5, 6]] for item in sublist]
all_true = all([True, False, True])
factorial = lambda n: 1 if n == 0 else n * factorial(n - 1)
dict_from_lists = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
squared_list = list(map(lambda x: x**2, [1, 2, 3, 4]))
max_element = max([10, 5, 20, 15])
any_true = any([False, False, True])
sorted_reverse = sorted([3, 1, 4, 2], reverse=True)