遍历嵌套For语句

时间:2013-06-17 21:36:24

标签: python nested

我应该看看这个模型解决方案,以便为我的下一个班级工作。该程序返回32到126之间的ASCII值。直到“for statements”我才理解它。请问有人可以帮我解决一下吗?我知道它与创建四列有关,但我认为在继续之前理解它的每一点都是有益的。

非常感谢。

START = 32

END = 126


def GiveAscii(start=START, end=END, width=4):

    """Returns an ascii chart as a string. Readable."""

    entries = end - start +1
    entries_per_column = entries/width
    if entries % width:
        entries_per_column += 1
    ret = []
    for row in range(entries_per_column):
        for column in range(width):
            entry = entries_per_column * column + row + start
            if entry > end:
                break
            ret += ["%3d = %-6s" % (entry, chr(entry))]
        ret += ['\n']
    return ''.join(ret)

def main():
    print GiveAscii()

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:0)

第一个列举范围从零到entries_per_column的值作为名为row的变量

对于每一行,有一个从零到width的值的枚举,作为名为column的变量

所以这就是创建一个二维矩阵 - 应该是相当容易消化的。

对于column中的每个row,该空间中的值将分配给变量entry。如果entry未超过矩阵的最大值,则将其作为列表放入返回列表ret内。在此ret之后给出换行符,以便可以直观地创建新行(当打印出ret时)。因此,该程序创建了一个列表ret,其中包含一个二维值矩阵 - 一些row个列表,每个列表都包含一些名为column的单值列表s,里面有entries

我希望这很清楚!

答案 1 :(得分:0)

我决定评论您的代码以确定它是否可以帮助您

START = 32

END = 126

# A function to return a string which represents an asci grid
def GiveAscii(start=START, end=END, width=4):

    """Returns an ascii chart as a string. Readable."""
    # The number of entries is the end minus the start plus one
    entries = end - start +1
    # Doing an integer devide provides us with the floor of the entries per column
    entries_per_column = entries/width
    # If our division was not even
    if entries % width:
        # We need to add an extra entry per column
        entries_per_column += 1
    # Initialize our array
    ret = []
    # For every row
    for row in range(entries_per_column):
        # Go through every column
        for column in range(width):
            # Do this math to create this entry, multiply first!
            entry = entries_per_column * column + row + start
            # If the entry is larger than the value end
            if entry > end:
                # Leave this column
                break
            # Not really sure what this formatting is but it is a formatting statment
            # Char casts your number as a character
            ret += ["%3d = %-6s" % (entry, chr(entry))]
         # When we are done with our column print and endline charachter
         ret += ['\n']
    # Return your array
    return ''.join(ret)

def main():
    print GiveAscii()

if __name__ == '__main__':
    main()