开始 类 在多行上打印一个字符串

Beginning classes Printing a string on multiple lines

在python

我正在家里学习 edx 课程,以扩展我的编程技能。我 运行 的一项作业让我很困惑。目标是能够插入一个整数并打印出一个时间 table。

此 table 将被分成列和行。我可以 assemble 将我需要的值转换成一个字符串,用于所有数字乘以给定的变量输入。我添加了在整数之间调用的选项卡。

现在这是一个字符串,我不能让它分成不同大小的裂缝并根据最初输入的不同值进行打印。

我尝试了文本换行,但无论我如何根据不同的示例放置它,都会出现错误。

请帮我找到一个解决方案并解释它为什么有效。我正在尝试学习这不是一个可以解决问题的代码行,但让我仍然一无所知。

我在 slack 中找到的

None 的提示中 class 包含目前课程中列出的术语或命令。很多没有列出。

这是我所拥有的,请忽略因尝试不同的解决方案而剩下的额外内容。

   mystery_int = 5

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#This is a tough one! Stick with it, you can do it!
#
#Write a program that will print the times table for the
#value given by mystery_int. The times table should print a
#two-column table of the products of every combination of
#two numbers from 1 through mystery_int. Separate consecutive
#numbers with either spaces or tabs, whichever you prefer.
#
#For example, if mystery_int is 5, this could print:
#
#1  2   3   4   5
#2  4   6   8   10
#3  6   9   12  15
#4  8   12  16  20
#5  10  15  20  25
#
#To do this, you'll want to use two nested for loops; the
#first one will print rows, and the second will print columns
#within each row.
#
#Hint: How can you print the numbers across the row without
#starting a new line each time? With what you know now, you
#could build the string for the row, but only print it once
#you've finished the row. There are other ways, but that's
#how to do it using only what we've covered so far.
#
#Hint 2: To insert a tab into a string, use the character
#sequence "\t". For example, "1\t2" will print as "1    2".
#
#Hint 3: Need to just start a new line without printing
#anything else? Just call print() with no arguments in the
#parentheses.
#
#Hint 4: If you're stuck, try first just printing out all
#the products in one flat list, each on its own line. Once
#that's working, then worry about how to organize it into
#a table.


#Add your code here!
import textwrap
a = mystery_int
b = 1
c = 0
d = 1
e = ""
f = ""
g = "" 
h = "\t"
j = 1
k = a*2

for b in range(1,a + 1):
    for c in range(1,a+1):
        d = b * c
        e +=str(d)+","
        f = str(e)

g = str.replace(f,"," ,"\t")

#textwrap.wrap(g,10)
#print(g[0:int(k)])
print(g[:k])

大功告成,您只需收集列表中每一行的值,然后在内循环的每次迭代后打印行值。

鉴于您基本上已经有了一个完整的解决方案,除了一些小错误,我将提供一个完整的解决方案演练,并附上解释。

表示法:我们将使用 mystery_int 而不是 a,我们会将 b(外循环增量)更改为 i,并且 c(内循环增量)到j,与约定保持一致:

mystery_int = 5

for i in range(1, mystery_int+1):
    row = [str(i)]
    for j in range(2, mystery_int+1):
        row = row + [str(i*j)]
    print('\t'.join(row))

输出:

1   2   3   4   5
2   4   6   8   10
3   6   9   12  15
4   8   12  16  20
5   10  15  20  25

外循环 (i) 遍历行,内循环 (j) 遍历列。
在每一行,我们需要一个新列表 row,它开始时只有一个元素。第一个元素是我们要乘以的数字(因此第 1 行的第一个元素是 1,第 2 行的第一个元素是 2,依此类推)。

请注意,我们正在将所有整数转换为字符串 (i --> str(i)),因为我们最终希望将每一行打印为白色 space-分隔序列。

  • 任何时候使用白色打印space,即使要打印的内容由数字组成,您也需要将该内容转换为字符串表示形式。 (您已经在您的代码中这样做了,但这一点值得重申,因为它是一个常见的绊脚石。)

现在,在内循环 (j) 中,计算第一列 (i*2i*3、...、i*mystery_int 之后每一列的乘积).对于内部循环的每次传递,将新产品添加到 row。当我们完成内部循环时,我们将获得以整数 i.

开头的行的乘法级数的完整列表

此时,在移动到下一行之前,打印出当前行。 join() 方法是连接列表中元素的常用方法,使用 . 之前指定的分隔符。

  • 例如,' '.join(row) 将创建一个由单个 space 分隔值组成的字符串:

    ' '.join(["1","2","3","4","5"])
    # '1 2 3 4 5'
    
  • 我选择使用制表符分隔的字符串,因为打印输出的格式更好。 (由于某些行有两位数而其他行只有一位数,单个 space 分隔符会使列看起来未对齐。)

备注:

  • 从教学的角度来看,用 "base" 整数 i: row = [str(i)] 初始化每个新的 row 似乎更直观。这为内部循环内随后的其余行计算提供了视觉锚定。但是,简单地初始化一个空列表 row = [],然后使用 j = 1:

    开始内部循环也是有效的(可能有点 "cleaner")
    for i in range(1, mystery_int+1):
        row = []
        for j in range(1, mystery_int+1):
            row = row + [str(i*j)]
        print('\t'.join(row))
    
  • 使用附加模块,可以使用更简单且通常更快的代码实现相同的目标。看来您正在使用 Python 标准库,这就是为什么我在主要解决方案中保持基础知识。但是考虑到乘法 table 实际上是两个相同向量的外积,我们也可以使用 Numpy 模块,它提供了许多快速的数学运算:

    import numpy as np
    print(np.array2string(np.outer(np.arange(1, mystery_int+1), 
                                   np.arange(1, mystery_int+1)), 
                          separator='\t'))
    

要点是,当您开始更多地使用 Python 来完成给定任务时,而不是简单地学习编程基础知识,有理由假设那里有一个模块可以定制适合您的需求,这可以真正节省时间。 just about everything!

有一个 Python 模块
for i in range(1, mystery_int + 1):
    row_string = ""
    for j in range(1, mystery_int + 1):
        product = i * j
        row_string += str(product) + "\t"
    print(row_string)