Python 正确格式化的乘法表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20415384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:22:55  来源:igfitidea点击:

Properly formatted multiplication table

pythonstringalgorithmpython-3.xformatting

提问by

How would I make a multiplication table that's organized into a neat table? My current code is:

我将如何制作一个组织成一个整洁表格的乘法表?我目前的代码是:

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col)
    print()

This correctly multiplies everything but has it in list form. I know I need to nest it and space properly, but I'm not sure where that goes?

这正确地将所有内容相乘,但以列表形式显示。我知道我需要正确地嵌套它并留出空间,但我不确定那去哪儿了?

回答by John La Rooy

Quick way (Probably too much horizontal space though):

快速方法(虽然可能水平空间太大):

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col, end="\t")
    print()

Better way:

更好的方法:

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    print(*("{:3}".format(row*col) for col in range(1, n+1)))

And using f-strings (Python3.6+)

并使用 f-strings (Python3.6+)

for row in range(1, n + 1):
    print(*(f"{row*col:3}" for col in range(1, n + 1)))

回答by doptimusprime

For this print as following

对于此打印如下

 print "%d X %d"%(row, col)

It will print as 2 X 3.

它将打印为 2 X 3。

回答by Fraxtil

You can accomplish the effect you're looking for much more easily by putting one of the loops inside the printcall.

通过在print调用中放置循环之一,您可以更轻松地实现您正在寻找的效果。

n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1, n+1):
    print('\t'.join(str(row * col) for col in range(1, n+1)))

This creates a generator that yields the string values of row*1, row*2, ... row*n, joins each of those values with a tab character, and passes the resulting string to print().

这将创建一个生成器,生成row*1, row*2, ...的字符串值row*n,将这些值中的每一个与制表符连接起来,并将结果字符串传递给print()

回答by Aaron Hall

Gnibbler's approach is quite elegant. I went for the approach of constructing a list of list of integers first, using the range function and taking advantage of the step argument.

Gnibbler 的方法非常优雅。我首先采用了构造整数列表的方法,使用 range 函数并利用 step 参数。

for n = 12

对于 n = 12

import pprint
n = 12
m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
pprint.pprint(m)
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60],
 [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72],
 [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84],
 [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96],
 [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108],
 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
 [11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132],
 [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144]]

Now that we have a list of list of integers that is in the form that we want, we should convert them into strings that are right justified with a width of one larger than the largest integer in the list of lists (the last integer), using the default argument of ' 'for the fillchar.

现在我们有一个我们想要的形式的整数列表,我们应该将它们转换为右对齐的字符串,宽度比列表列表中的最大整数(最后一个整数)大一,使用' '填充字符的默认参数。

max_width = len(str(m[-1][-1])) + 1
for i in m:
    i = [str(j).rjust(max_width) for j in i]
    print(''.join(i))

   1   2   3   4   5   6   7   8   9  10  11  12
   2   4   6   8  10  12  14  16  18  20  22  24
   3   6   9  12  15  18  21  24  27  30  33  36
   4   8  12  16  20  24  28  32  36  40  44  48
   5  10  15  20  25  30  35  40  45  50  55  60
   6  12  18  24  30  36  42  48  54  60  66  72
   7  14  21  28  35  42  49  56  63  70  77  84
   8  16  24  32  40  48  56  64  72  80  88  96
   9  18  27  36  45  54  63  72  81  90  99 108
  10  20  30  40  50  60  70  80  90 100 110 120
  11  22  33  44  55  66  77  88  99 110 121 132
  12  24  36  48  60  72  84  96 108 120 132 144

and demonstrate the elasticity of the spacing with a different size, e.g. n = 9

并展示不同尺寸的间距的弹性,例如 n = 9

n=9
m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
for i in m:
    i = [str(j).rjust(len(str(m[-1][-1]))+1) for j in i]
    print(''.join(i))

  1  2  3  4  5  6  7  8  9
  2  4  6  8 10 12 14 16 18
  3  6  9 12 15 18 21 24 27
  4  8 12 16 20 24 28 32 36
  5 10 15 20 25 30 35 40 45
  6 12 18 24 30 36 42 48 54
  7 14 21 28 35 42 49 56 63
  8 16 24 32 40 48 56 64 72
  9 18 27 36 45 54 63 72 81

回答by Pitarou

Your problem is that print adds a newline, and you don't want all those newlines.

您的问题是 print 添加了换行符,而您不想要所有这些换行符。

One way to do it is to build a string for each line, and then print out the whole line in one print statement.

一种方法是为每一行构建一个字符串,然后在一个打印语句中打印出整行。

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    s = ''
    for col in range(1,n+1):
        s += '{:3} '.format(row * col)
    print(s)

The magic is in the '{:3} '.formatbit. It's tricky, so here's a tutorial: http://ebeab.com/2012/10/10/python-string-format/

魔法就在这'{:3} '.format一点上。这很棘手,所以这里有一个教程:http: //ebeab.com/2012/10/10/python-string-format/

Here's the code in action:

这是运行中的代码:

Please enter a positive integer between 1 and 15: 4
  1   2   3   4 
  2   4   6   8 
  3   6   9  12 
  4   8  12  16 

回答by Shahab

n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
    for col in range(1,n+1):
        print(row*col, "\t",end = "")      
    print()

#the "\t" adds a tab each time, and the end = "" prints your string horizontally.

回答by Floam

Or you could just do this (not as simplistic as the others but it works):

或者你可以这样做(不像其他人那么简单,但它有效):

def main():

    rows = int(input("Enter the number of rows that you would like to create a multiplication table for: "))
    counter = 0
    multiplicationTable(rows,counter)

def multiplicationTable(rows,counter):

    size = rows + 1

    for i in range (1,size):
        for nums in range (1,size):
            value = i*nums
            print(value,sep=' ',end="\t")
            counter += 1
            if counter%rows == 0:
                print()
            else:
                counter
main()

回答by GNUdelman

this one looks pretty neat:

这个看起来很整洁:

   print '\t\t\t======================================='
   print("\t\t\t\tMultiplication Tables")
   print '\t\t\t=======================================\n'
   for i in range(1,11):
       print '\t', i,
   print
   print("___________________________________________________________________________________________________________________")

   for j in range(1,11):
       print("\n")
       print j, '|',
       for k in range(1,11):
           print '\t', j * k,
   print("\n")

回答by Yehuda Katz

Here's my take for organizing the output:

这是我对组织输出的看法:

for row in range(1, 11):
    for col in range(1, 11):
        num = row * col
        if num < 10: blank = '  '       # 2 blanks
        else:
            if num < 100: blank  = ' '  # 1 blank
        print(blank, num, end = '')     # Empty string
    print()                             # Start a new line

回答by MJMacarty

This works pretty well for a standard multiplication table that is easy to explain in terms of coding for beginners:

这对于标准乘法表非常有效,该表很容易在初学者编码方面进行解释:

x = 12
y = 12
print ' ',
for fact in range(1, x+1):
    str(fact).rjust(6),
for fact in range(1, y+1):
    print
    print fact,
    for i in range(1,y+1):
        product = i * fact
        print str(product).rjust(5),
    print