【问题标题】:How to input elements of Matrix in Python using List?如何使用List在Python中输入矩阵的元素?
【发布时间】:2017-10-01 04:13:43
【问题描述】:

我只是想在一个二维数组(列表)中获取输入,维度为 n*m。例如,

1 2 3

4 5 6

1 2 3

7 8 9

对于 4*3 矩阵。

我也希望输入格式相同。相同行元素之间的空格和两行之间的“Enter”。 蟒蛇新手。一直在寻找相关的soln。但没有找到。 提前致谢。

【问题讨论】:

  • 重复的1 2 3 行是故意的吗?
  • 不清楚您要问什么。您能否添加一个MCVE,其中包含您尝试使用的代码、实际结果以及预期结果或输出?

标签: python


【解决方案1】:

希望这篇文章对您有所帮助:

n,m=map(int,input().split())
l=["0"]*n
j=0
for i in range(0,n):
    l[i]=["0"]*m
    l[i]=list(input().split())
print (l)

【讨论】:

    【解决方案2】:

    你可以这样做:

    arr = [[], [], []]
    for i in range(4):
      for j in range(3):
        arr[i].append(input())
    

    我没有尝试,但它应该可以工作:)

    【讨论】:

      【解决方案3】:

      如果您还不熟悉在 python 中读取文件,这里有一种常见的有效方法。 with 语句为您打开和关闭文件。然后,遍历这些行并使用 split() 函数,该函数将返回由空格分隔的行列表。然后只需将它们附加到列表中,即可生成列表列表!逻辑中不需要维度,因此此代码适用于任何维度组合。

      with open('input.txt') as f:
          lines = f.readlines()
      desired_list = []
      for line in lines:
          line = line.split(' ')
          # if you want to cast the input as an int, 
          # use the line below instead
          # line = [int(x) for x in line.split(' ')]
          desired_list.append(line)`
      

      【讨论】:

      • 其实我想从键盘本身输入矩阵。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多