格式正确的乘法表

时间:2013-12-06 03:26:23

标签: python string algorithm python-3.x formatting

如何将乘法表组织成一张整齐的表格?我目前的代码是:

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()

这正确地将所有内容相乘,但是以列表形式存在。我知道我需要正确地嵌套它和空间,但我不确定它到底在哪里?

19 个答案:

答案 0 :(得分:9)

快捷方式(虽然可能太多水平空间):

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()

更好的方式:

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)))

使用f-strings(Python3.6 +)

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

答案 1 :(得分:4)

Gnibbler的方法非常优雅。我首先使用范围函数并利用步骤参数来构建整数列表的方法。

对于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]]

现在我们有一个包含我们想要的形式的整数列表, 我们应该将它们转换为宽度正确对齐的字符串 比列表列表中的最大整数(最后一个整数)大一个, 使用' '的默认参数作为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

并证明具有不同尺寸的间距的弹性,例如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

答案 2 :(得分:1)

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

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()

答案 3 :(得分:1)

这个看起来非常整洁:

   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")

答案 4 :(得分:1)

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

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

答案 5 :(得分:1)

创建算术表要简单得多,但我认为我应该发布我的答案,尽管这个问题有很多答案,因为没有人谈论过表的限制。

将用户输入作为整数

num = int(raw_input("Enter your number"))

设置表格的限制,我们希望计算所需数量的表格

lim = int(raw_input("Enter limit of table"))

从索引1开始的迭代计算

在此,我使用格式切片来调整数字之间的空白,即{:2}以进行两个空格调整。

for b in range(1, lim+1):
    print'{:2} * {:2} = {:2}'.format(a, b, a*b)

最终代码:

num = int(raw_input("Enter your number"))
lim = int(raw_input("Enter limit of table"))
for b in range(1, lim+1):
    print'{:2} * {:2} = {:2}'.format(a, b, a*b)

<强>输出:

Enter your number 2
Enter limit of table 20
 2 *  1 =  2
 2 *  2 =  4
 2 *  3 =  6
 2 *  4 =  8
 2 *  5 = 10
 2 *  6 = 12
 2 *  7 = 14
 2 *  8 = 16
 2 *  9 = 18
 2 * 10 = 20
 2 * 11 = 22
 2 * 12 = 24
 2 * 13 = 26
 2 * 14 = 28
 2 * 15 = 30
 2 * 16 = 32
 2 * 17 = 34
 2 * 18 = 36
 2 * 19 = 38
 2 * 20 = 40

答案 6 :(得分:0)

这对于标准乘法表非常有效,这对于初学者的编码很容易解释:

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

答案 7 :(得分:0)

使用此代码。它比这里的任何答案都好得多。我上学时必须这样做,在投入约4个小时后,我可以告诉您它确实运行得很好。

def returnValue(int1, int2):
    return int1*int2

startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")

int1 = int(startingPoint)
int2 = int(endingPoint)

spacing = "\t"

print("\n\n\n")
if int1 == int2:
    print("Your integers cannot be the same number. Try again. ")
    

if int1 > int2:
    print("The second number you entered has to be greater than the first. Try again. ")


for column in range(int1, int2+1, 1):  #list through the rows(top to bottom)
    
    if column == int1:
            for y in range(int1-1,int2+1):
                if y == int1-1:
                    print("", end=" \t") 
                    
                else: 
                    individualSpacing = len(str(returnValue(column, y)))
                    print(y, " ", end=" \t")
            print()
            
    print(column, end=spacing)

    
    for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
        #print("second range val: {:}".format(row))
        
            individualMultiple = returnValue(row, column)
            print(individualMultiple, " ", end = "\t")
        
    print("")

输出: Result after entering 5 and 8

或者, Result after entering 40 and 45

答案 8 :(得分:0)

hidden

答案 9 :(得分:0)

table = int(input("Enter a Positive Number: "))
for i in range(1,11):
    print(table, 'X', i, '=', table*i)
print("See you later, Alligator!")

答案 10 :(得分:0)

这对我来说很好:

num, b, c, count = int(input('Enter a number')), '  ', '   ', 0
for i in range(1, num+1):
    if i > 9:
        b = b + str(i) + '   '
        c = c + str(i) + '|'
    else:
        b = b + str(i) + '    '
        c = c + str(i) + ' |'
    for a in range(1, num+1):
        d = str(a*i)
        for letter in d:
            count += 1
        c = c + str(a*i) + ' '*(5-count)
        count = 0
    c = c + '\n   '
print((' ')*4 + b)
print((' ')*6 + ('-'+ '    ')*num)
print(c)

最多可乘以99。

输入数字12时输出:

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

答案 11 :(得分:0)

for i in range(1, 10) :
    for j in range(1, 10):
        print(repr(i*j).rjust(4),end=" ")
print()
print()

输出:

  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 

或这个

for i in range(1, 11):
    for j in range(1, 11):
        print(("{:6d}".format(i * j,)), end='')
print()

结果是:

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

答案 12 :(得分:0)

乘法表有很多答案。在这里,我通过调用函数来完成。随时改善。

    num = int(input('Please enter time tables for printing: '))
    upperLimit = int(input('Please enter upper limit: '))

    def printTable(num, upperLimit):   
        for i in range(0, upperLimit+1):
            print(num, 'x', i, '=', num * i)

    def main():
        printTable(num, upperLimit)

    main()    

答案 13 :(得分:0)

for x in range(1, 11):
        for y in range(1, 11):
            z = x * y
            print(z, end="\t")
        print() #creates the space after the loop

上面的代码会产生这样的结果:

答案 14 :(得分:0)

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.

答案 15 :(得分:0)

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

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

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)

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

以下是行动中的代码:

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 

答案 16 :(得分:0)

通过将其中一个循环置于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)))

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

答案 17 :(得分:0)

对于此印刷品如下

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

它将打印为2 X 3。

答案 18 :(得分:-2)

另外:

class Library < Array
  attr_accessor :authors

  def initialize(**args)
     @authors = {key1: 'val1', key2: 'val2'}
     super(args)
  end

end