Python的 5 种高级用法,效率提升没毛病!
【摘要】 任何编程语言的高级特征通常都是通过大量的使用经验才发现的。比如你在编写一个复杂的项目,并在 stackoverflow 上寻找某个问题的答案。然后你突然发现了一个非常优雅的解决方案,它使用了你从不知道的 Python 功能!这种学习方式太有趣了:通过探索,偶然发现什么。下面是 Python 的 5 种高级特征,以及它们的用法。Lambda 函数Lambda 函数是一种比较小的匿名函数——匿名...
print(x(5, 6)) # prints 30
x = lambda a : a*3 + 3
print(x(3)) # prints 12
return a * a
x = map(square_it_func, [1, 4, 7])
print(x) # prints [1, 16, 47]
def multiplier_func(a, b):
return a * b
x = map(multiplier_func, [1, 4, 7], [2, 5, 8])
print(x) # prints [2, 20, 56] 看看上面的示例!我们可以将函数应用于单个或多个列表。实际上,你可以使用任何 Python 函数作为 map 函数的输入,只要它与你正在操作的序列元素是兼容的。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Function that filters out all numbers which are odd
def filter_odd_numbers(num):
if num % 2 == 0:
return True
else:
return False
filtered_numbers = filter(filter_odd_numbers, numbers)
print(filtered_numbers)
# filtered_numbers = [2, 4, 6, 8, 10, 12, 14]
# Easy joining of two lists into a list of tuples
for i in izip([1, 2, 3], [ a , b , c ]):
print i
# ( a , 1)
# ( b , 2)
# ( c , 3)
# The count() function returns an interator that
# produces consecutive integers, forever. This
# one is great for adding indices next to your list
# elements for readability and convenience
for i in izip(count(1), [ Bob , Emily , Joe ]):
print i
# (1, Bob )
# (2, Emily )
# (3, Joe )
# The dropwhile() function returns an iterator that returns
# all the elements of the input which come after a certain
# condition becomes false for the first time.
def check_for_drop(x):
print Checking: , x
return (x > 5)
for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]):
print Result: , i
# Checking: 2
# Checking: 4
# Result: 6
# Result: 8
# Result: 10
# Result: 12
# The groupby() function is great for retrieving bunches
# of iterator elements which are the same or have similar
# properties
a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5])
for key, value in groupby(a):
print(key, value), end= )
# (1, [1, 1, 1])
# (2, [2, 2, 2])
# (3, [3, 3])
# (4, [4])
# (5, [5])
numbers = list()
for i in range(1000):
numbers.append(i+1)
total = sum(numbers)
# (2) Using a generator
def generate_numbers(n):
num, numbers = 1, []
while num < n:
numbers.append(num)
num += 1
return numbers
total = sum(generate_numbers(1000))
# (3) range() vs xrange()
total = sum(range(1000 + 1))
total = sum(xrange(1000 + 1))
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)