【问题标题】:Python: Parse string to arrayPython:将字符串解析为数组
【发布时间】:2017-04-04 03:13:05
【问题描述】:

我目前在将字符串解析为 numpy 数组时遇到问题。

字符串如下所示:

input = '{{13,1},{2,1},{4,4},{1,7},{9,1}}'

字符串表示一个稀疏向量,其中向量本身由大括号分隔。每个条目本身由大括号分隔,指示哪些索引具有哪些条目。列表中的第一项编码向量的维度。

在上面的例子中,向量的长度为 13 和 4 个不为 0 的条目。

output = np.array([0,7,1,0,4,0,0,0,0,1,0,0,0])

将其解析为数组后,我必须将其解析为密集格式的字符串,格式为:

stringoutput = '{0,7,1,0,4,0,0,0,0,1,0,0,0}'

虽然我设法将 numpy 数组解析为字符串,但我遇到了括号错误的问题(即内置 array2string 函数使用 [],而我需要 {})

我愿意接受任何有用的建议,有效地解决这个问题(即使是大型稀疏向量)。

谢谢。

\edit:给定的向量总是一维的,即第一个 {} 中的第二个数字总是 1。(你只需要 1 个索引来定位元素的位置)

【问题讨论】:

  • 它们总是一维的吗?

标签: python arrays string numpy


【解决方案1】:

这是一个numpythonic方式:

In [132]: inp = '{{13,1},{2,1},{4,4},{1,7},{9,1}}'

# Relace the brackets with parenthesis in order to convert the string to a valid python object.
In [133]: inp = ast.literal_eval(inp.replace('{', '(').replace('}', ')'))
# Unpack the dimention and rest of then values from input object
In [134]: dim, *rest = inp
# Creat the zero array based on extracted dimention 
In [135]: arr = np.zeros(dim)
# use `zip` to collecte teh indices and values separately in order to be use in `np.put`
In [136]: indices, values = zip(*rest)

In [137]: np.put(arr, indices, values)

In [138]: arr
Out[138]: 
array([[ 0.],
       [ 7.],
       [ 1.],
       [ 0.],
       [ 4.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 1.],
       [ 0.],
       [ 0.],
       [ 0.]])

【讨论】:

    【解决方案2】:

    我喜欢@Kasramvd 的方法,但我想我也会把它放在那里:

    In [116]: r = (list(map(int, a.split(','))) for a in input[2:-2].split('},{'))
    
    In [118]: l = np.zeros(next(r)[0], np.int)
    
    In [119]: for a in r:
         ...:     l[a[0]] = a[1]
         ...:    
    
    In [122]: s = '{' + ','.join(map(str, l)) + '}'
    
    In [123]: s
    Out[123]: '{0,7,1,0,4,0,0,0,0,1,0,0,0}'
    

    【讨论】:

      【解决方案3】:

      这是基于@Kasramvd 的回答。我调整了其他值的填充方式。

      来自@Kasramvd

      import numpy as np
      import ast
      
      inp = '{{13,1},{2,1},{4,4},{1,7},{9,1}}'
      inp = ast.literal_eval(inp.replace('{', '(').replace('}', ')'))
      dim, *rest = inp
      

      我的调整

      a = np.zeros(dim, dtype=int)
      r = np.array(rest)
      a[r[:, 0], 0] = r[:, 1]
      
      a
      
      array([[0],
             [7],
             [1],
             [0],
             [4],
             [0],
             [0],
             [0],
             [0],
             [1],
             [0],
             [0],
             [0]])
      

      在一维中

      a = np.zeros(dim[0], dtype=int)
      r = np.array(rest)
      a[r[:, 0]] = r[:, 1]
      
      a
      
      array([0, 7, 1, 0, 4, 0, 0, 0, 0, 1, 0, 0, 0])
      

      【讨论】:

        猜你喜欢
        • 2017-02-02
        • 1970-01-01
        • 2012-10-14
        • 2014-03-04
        • 2019-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多