【问题标题】:matrix print convert from input one by one to input space-separated矩阵打印从输入一一转换为输入空格分隔
【发布时间】:2021-03-18 15:55:33
【问题描述】:

我有这段代码可以打印输入值的矩阵。现在值是一一输入的,但我想将其转换为以空格分隔的输入。试了很多方法,都不行,怎么办?

print("This program prints a matrix in aligned rows and columns")
while True:
    try:
        nbrRows = int(input("What is the number of rows: "))
        if nbrRows <= 0:
            print("The number of rows cannot be negative or zero")
            continue
        else:
            break
    except:
        print("You did not enter an integer value")
    continue
while True:
    try:
        nbrCols = int(input("What is the number of columns: "))
        if nbrCols <= 0:
            print("The number of columns cannot be negative or zero")
            continue
        else:
            break
    except:
        print("You did not enter an integer value")
        continue

print("Please enter the elements one by one at the prompts")
nbrElements = nbrRows * nbrCols
count = 0
outputString = ""

for i in range(nbrRows):
    for j in range(nbrCols):
        while True:
            try:
                elem = int(input("? "))
                break
            except:
                print("Please enter an integer value")
        outputString += str(elem) + "\t"
    outputString += "\n"

print(outputString)

感谢您的帮助。

【问题讨论】:

  • 看起来您的代码运行良好。它产生分隔的输出空间。

标签: python python-3.x loops matrix


【解决方案1】:

您可以通过要求用户以逗号分隔输入元素然后将它们拆分为打印输出来实现此目的。

elem = input ("Please enter the elements comma separate : ")
element = elem.split(",")
nbrElements = nbrRows * nbrCols
count = 0
outputString = ""


for i in range(nbrRows):
    for j in range(nbrCols):
        for e in element :
            outputString += str(e) + "\t"
        outputString += "\n"

输出

This program prints a matrix in aligned rows and columns
What is the number of rows: 2
What is the number of columns: 2
Please enter the elements comma seperated : 1,2,3,4
1   2   3   4   
1   2   3   4   
1   2   3   4   
1   2   3   4   

【讨论】:

  • 是的,它可以工作,但是正如您所见,您需要一个一个地输入元素,我希望它可以一次性输入,并用空格分隔。我无法这样做。
  • 您可以向用户询问逗号分隔的输入,然后将它们拆分为打印输出。
猜你喜欢
  • 2023-03-28
  • 2015-08-17
  • 1970-01-01
  • 2016-06-17
  • 2022-08-11
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2022-11-20
相关资源
最近更新 更多