# 1 with ...: for ...: if ...: try: except: else:
result = [] for item in item_list: new_item = do_something_with(item) result.append(item)
from functools import reduce summation = reduce(lambda x, y: x + y, numbers)
>>> a = list(range(10)) >>> 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))
另外,如果你在迭代组合的序列,还有product(),permutations(),combinations()可以用。
结论
1.大多数情况下是不需要写for循环的。
2.应该避免使用for循环,这样会使得代码有更好的阅读性。
行动
1.再看一遍你的代码,找出任何以前凭直觉写下for循环的地方,再次思考一下,不用for循环再写一遍是不是有意义的。
2.分享你很难不使用for循环的例子。
以上就是python中关于for循环的实例详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于python中关于for循环的实例详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did84818