文章来源:Python 技术
自从我开始探索 Python 中惊人的语言功能已经有一段时间了。一开始,我给自己一个挑战,目的是让我练习更多的 Python 语言功能,而不是使用其他编程语言的编程经验。这让事情变得越来越有趣!代码变得越来越简洁,代码看起来更加结构化和规范化。下面我将会介绍这些好处。
通常如下使用场景中会用到 for 循环:
在一个序列来提取一些信息。
从一个序列生成另一个序列。 写 for 已成习惯。
较少的代码量 更好的代码可读性 更少的缩进(对 Python 还是很有意义的)
# 1
with ...:
for ...:
if ...:
try:
except:
else:
result = []
for item in item_list:
new_item = do_something_with(item)
result.append(item)
result = [do_something_with(item) for item in item_list]
doubled_list = map(lambda x: x * 2, old_list)
from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)
10)) > a = list(range(
> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> all(a)
False
> any(a)
True
> max(a)
9
> min(a)
0
> list(filter(bool, a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
> set(a)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> dict(zip(a,a))
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
> sorted(a, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
> str(a)
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
> sum(a)
45
results = []
for item in item_list:
# setups
# condition
# processing
# calculation
results.append(result)
def process_item(item):
# setups
# condition
# processing
# calculation
return result
results = [process_item(item) for item in item_list]
results = []
for i in range(10):
for j in range(i):
results.append((i, j))
results = [(i, j)
for i in range(10)
for j in range(i)]
# finding the max prior to the current item
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = []
current_max = 0
for i in a:
current_max = max(i, current_max)
results.append(current_max)
# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
def max_generator(numbers):
current_max = 0
for i in numbers:
current_max = max(i, current_max)
yield current_max
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = list(max_generator(a))
from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))
如果你觉得文章还不错,请大家 点赞、分享、留言下,因为这将是我持续输出更多优质文章的最强动力!
我们还为大家准备了Python资料,感兴趣的小伙伴快来找我领取一起交流学习哦!
往期推荐