【问题标题】:how do I input custom arrays into rows & columns in 2d character array如何将自定义数组输入到二维字符数组的行和列中
【发布时间】:2022-11-18 02:18:17
【问题描述】:
Rows = int(input("give the number of rows:"))
Columns = int(input("Give the number of columns:"))
matrix = []

for i in range(Rows):
        matrix.append(['a', 'b', 'c','d', 'e'])
        
    for vector in matrix:
        print(matrix)

这是输出:

give the number of rows:3
Give the number of columns:3
[['a', 'b', 'c', 'd', 'e']]
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

[当用户输入 3x3 的行和列时需要像这样]

【问题讨论】:

  • 什么是预期的输出?您是否期待一个 3 项数组,其中项是长度为 3 的向量?
  • 您的代码缩进使其无效。
  • 抱歉。我对此很陌生。
  • 没问题!下面发布了一个似乎可以解决您的问题的提交。

标签: python arrays matrix


【解决方案1】:

有多种方法可以初始化具有特定大小的数组。下面是一种更简洁的方法。

Rows = int(input("Give the number of rows:"))
Columns = int(input("Give the number of columns:"))
matrix = [["a"]*Rows]*Columns

print(matrix)

这将给出输出

Give the number of rows:3
Give the number of columns:3
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]

这给出了您正在寻找的数组大小。

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多