简体   繁体   English

Python 2.7:如何使用避免循环的多次迭代

[英]Python 2.7: How to use avoid multiple iterations of a loop

I have the following list which say I want to process somehow and then print out the elements: 我有以下列表,说我想以某种方式处理然后打印出元素:

mylist = [1,2,3,4,5,6]
def increment_list(l, amount):
    return [x + amount for x in l]

def print_incremented_list(l):
    for item in l:
        print(item)

l = increment_list(mylist, 1)
print_incremented_list(l)

one other way to write this would be 另一种写这个的方式是

print_incremented_list(increment_list(mylist, 1))

The issue I have with the one above is that the function calls are nested within each other which adds a bit of complexity. 我上面的问题是,函数调用相互嵌套,这增加了一点复杂性。 I find it easier to read when they are put on separate lines but that may be my preference. 我发现将它们放在单独的行中时更容易阅读,但这可能是我的偏爱。

The main problem is that both approaches suffer from having to go through the list twice, is there a way to avoid this without having to nest all the functionality inside a single function such as 主要问题是两种方法都必须两次遍历该列表,有没有一种方法可以避免这种情况,而不必将所有功能嵌套在一个功能中,例如

def increment_list(l, amount):
    incremented_list = []
    for a in l:
        incremented_list.append(a+amount)
        print(a+amount)
    return incremented_list

You can avoid going through the list twice by using a generator instead of a list (note the round brackets instead of the square ones): 您可以避免使用生成器而不是列表来浏览列表两次(请注意,圆括号而不是方括号):

def increment_list(l, amount):
    return (x + amount for amount in l)

With that, the functionality is cleanly separated, but only one pass through the list will be done. 这样一来,功能就完全分开了,但是只完成了一次遍历列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM