【问题标题】:How can I make a 3x3 matrix from a list of integers?如何从整数列表中制作 3x3 矩阵?
【发布时间】:2020-09-23 03:27:11
【问题描述】:

因此,我目前正在处理一些代码,但遇到了一个问题,如果不使用内置函数和 map 函数使用我生成的 lst 创建一个 3x3 矩阵,我就找不到方法。

    string = input('Please enter the numbers 1 through 9 in the order you want them in the square: ')
    lst = []
    for char in string:
        if char != ' ' and char.isdigit() == True:
            lst.append(int(char))
            
    while len(lst) != 9:
        string = input('Please enter the numbers 1 through 9 in the order you want them in the square: ')
        lst = []
        for char in string:
            if char != ' ' and char.isdigit() == True:
                lst.append(int(char))

让我们说我的string = 123 4 5 6 7 8 9

这意味着lst = [1,2,3,4,5,6,7,8,9]

我想打印我的程序:

1 2 3
4 5 6
7 8 9

使用来自lst的值

【问题讨论】:

    标签: python-3.x string list matrix printing


    【解决方案1】:

    如下使用列表推导式。

    [lst[3 * i: 3 * (i+1)] for i in range(3)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      相关资源
      最近更新 更多