【问题标题】:String to n*n matrix in pythonpython中的字符串到n * n矩阵
【发布时间】:2019-07-09 03:29:41
【问题描述】:

我是一名热爱编程的本科生。我今天遇到一个问题,我不知道如何解决这个问题。 我寻找“Python - 字符串到矩阵表示”(Python - string to matrix representation)寻求帮助,但我仍然对这个问题感到困惑。

问题出在以下几点:

给定一串空格分隔的数字,创建一个 nxn 矩阵(一个二维列表,其中列数与行数相同)并返回它。该字符串将包含整数的完美平方数。 int() 和 split() 函数可能很有用。

例子:

输入:'1 2 3 4 5 6 7 8 9'

输出:[[1,2,3],[4,5,6],[7,8,9]]

示例 2:

输入:'1'

输出:[[1]]

我的回答:

import numpy as np
def string_to_matrix(str_in):
    str_in_split = str_in.split()
    answer = []
    for element in str_in_split:
        newarray = []
    for number in element.split():
        newarray.append(int(number))
    answer.append(newarray)
    print (answer)

测试结果如下:

Traceback (most recent call last):
  File "/grade/run/test.py", line 20, in test_whitespace
    self.assertEqual(string_to_matrix('1      2 3   4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]

Stdout:
[[4]]

还有

Traceback (most recent call last):
  File "/grade/run/test.py", line 15, in test_small
    self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]

Stdout:
[[4]]

还有

Traceback (most recent call last):
  File "/grade/run/test.py", line 10, in test_one
    self.assertEqual(string_to_matrix('1'), [[1]])
AssertionError: None != [[1]]

Stdout:
[[1]]

还有

Traceback (most recent call last):
  File "/grade/run/test.py", line 25, in test_larger
    self.assertEqual(string_to_matrix('4 3 2 1 8 7 6 5 12 11 10 9 16 15 14 13'), [[4,3,2,1], [8,7,6,5], [12,11,10,9], [16,15,14,13]])
AssertionError: None != [[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]]

Stdout:
[[13]]

我仍然很困惑如何解决这个问题。非常感谢您的帮助!

【问题讨论】:

  • assertEqual 不会比较您的 print 结果,它使用 string_to_matrix 返回的值。 string_to_matrix 当前不返回任何内容,因此值为 None。更改return 的打印,您将开始获得更好的结果
  • 首先,您创建的函数仅print 给出答案,而不是return,因此断言将始终失败,因为None 是函数默认返回的。将print (answer) 替换为简单的return answer。其次,您似乎没有考虑到“字符串将包含整数的完美平方数”。

标签: python python-3.x numpy


【解决方案1】:

假设您不想要 numpy 并且想要使用列表列表:

def string_to_matrix(str_in):
    nums = str_in.split()
    n = int(len(nums) ** 0.5)
    return list(map(list, zip(*[map(int, nums)] * n)))

nums = str_in.split() 被任何空格分割,n 是结果的边长,map(int, nums) 将数字转换为整数(从字符串),zip(*[map(int, nums)] * n) 将数字分组为 n,@987654329 @ 将zip 生成的元组转换为列表。

【讨论】:

  • 非常感谢!您对“zip(*[map(int, nums)] * n) 将数字分组为 n, list(map(list, zip(*[map(int, nums)] * n))) 的解释将由 zip 生成的元组到列表中。”对我理解为什么可以这样写非常有帮助。
  • zip 的这种用法显示在 docs.python.org/3/library/itertools.html#itertools-recipesgrouper 配方中。不幸的是,它没有解释它是如何工作的。它利用了一些经常让用户感到困惑的 Python 特性。
【解决方案2】:

假设你想让这个动态。

str_in = '1 2 3 4 5 6 7 8 9'
a = str_in.split(" ")
r_shape = int(math.sqrt(len(a)))
np.array([int(x) for x in a]).reshape(r_shape, r_shape)

【讨论】:

    【解决方案3】:

    使用split,创建一维numpy数组,然后使用reshape

    >>> s = '1 2 3 4 5 6 7 8 9'
    >>> np.array([s.split(), dtype=int).reshape(3,3)
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    

    如果您不知道数组的大小,但您知道它是正方形(相同的宽度/高度),那么您可以使用math.sqrt 获取reshape 的输入:

    >>> import math
    >>> s = '1 2 3 4 5 6 7 8 9'
    >>> arr = np.array(s.split(), dtype=int)
    >>> size = int(math.sqrt(len(arr)))
    >>> arr.reshape(size, size)
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    

    【讨论】:

    • 您不需要int 映射或理解。只需要求np.array 生成一个整数数组:np.array(s.split(), dtype=int)
    • 好样的!感谢您的提示!
    【解决方案4】:

    鉴于您将始终获得整数的完美平方数:

    import numpy as np
    
    input_strings = '1 2 3 4 5 6 7 8 9'
    arr = np.array(input_strings.split(), dtype=int)
    n = int(len(arr) ** 0.5)
    arr.reshape(n, n)
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    

    注意:在您的情况下,str.split 最好不用明确的sep,以便在数字之间有多个空格时正常工作。

    【讨论】:

      【解决方案5】:
      import numpy as np
      def string_to_matrix(str_in):
         str_in_split = str_in.split()
         numbers = list(map(int, str_in_split))
         size = r_shape = int(np.sqrt(len(numbers)))
         return np.array(numbers).reshape(r_shape, r_shape)
      

      这就是为什么你总是得到:AssertionError: None != ...

      assertEqual(A, string_to_matrix("...")) 验证 A 是否等于 string_to_matrix 返回的值。在您的代码中,您不返回任何内容,所以它是 None

      另一个问题是如何拆分字符串,更简单的选择是将所有内容拆分并转换为数字,然后再整形为 sqrt(元素数)。这假设输入长度可以被分割形成一个nxn矩阵

      【讨论】:

        【解决方案6】:
        import math
        string = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16"
        stringItems = string.split(" ")
        numberOfItems = len(stringItems)
        if math.sqrt(numberOfItems) - int(math.sqrt(numberOfItems)) == 0:
            width = int(math.sqrt(numberOfItems))
            array = []
            finalArray = []
            for i in range (0, width):
                for j in range (0, width):
                    array.insert(j, stringItems[0])
                    stringItems.pop(0)
                finalArray.insert(i, array)
                array = []
            print finalArray
        else:
            print "I require a string with length equal to a square number please"
        

        【讨论】:

        • 回答 should consist of 不仅仅是代码转储。如果您认为这个问题问得不好,您可以标记它或发表评论。
        猜你喜欢
        • 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
        相关资源
        最近更新 更多