Is there a way to rewrite a list comprehension as a for loop?

I have a line of code like this:

list1=[string1[i:i+int1] for i in range(0, len(string1), int1)]

I remember my teacher saying that we should start new lines when there is 'for' so, is there a way to write this code that looks like:

for i in range(0, len(string1), int1):
    #something here

or something else?


You mean to extract a boring old regular for loop from a list-comprehension ?

list1=[string1[i:i+int1] for i in range(0, len(string1), int1)]

Becomes:

list1 = list()
for i in range(0, len(string1), int1):
    list1.append(string1[i:i+int1])

This would be useful if you wanted to add exception handling, logging, or more complex functions or behaviors while you iterate over your data.

For instance:

list1 = list()
for i in range(0, len(string1), int1):
    log.info('in loop: i={}'.format(i))
    try:
        data = string1[i:i+int1]
    except:
        log.error('oh no!')
        # maybe do something complex here to get some data anyway?
        data = complex_function(i)
    log.debug('appending to list: data={}'.format(data))
    list1.append(data)

But generally speaking the list-comprehension is a totally legitimate way to write that.


您必须先创建空列表,然后追加每次迭代。

list1 = []
for i in range(0, len(string1), int1):
    list1.append(string1[i:i+int1])

该列表理解将转化为:

l = []
for i in range(0, len(string1), int1):
    l.append(string1[i:i+int1])
链接地址: http://www.djcxy.com/p/31698.html

上一篇: Python与define相当

下一篇: 有没有办法将列表理解重写为for循环?