【问题标题】:Convert Python dict to csr matrix将 Python dict 转换为 csr 矩阵
【发布时间】:2016-03-12 01:20:02
【问题描述】:

我正在使用下面的函数将 (row, col):value 形式的字典转换为 csr 矩阵。 row 和 col 是 int,value 是 float。

def convert(term_dict):
    # Create the appropriate format for the COO format.
    data = []
    row = []
    col = []
    for k, v in term_dict.items():
        r = int(k[0][1:])
        c = int(k[1][1:])
        data.append(v)
        row.append(r-1)
        col.append(c-1)
    # Create the COO-matrix
    coo = coo_matrix((data, (row, col)))
    # Let Scipy convert COO to CSR format and return
    return csr_matrix(coo)

来自here。我来了

r = int(k[0][1:]) TypeError: 'int' object has no attribute 'getitem'

【问题讨论】:

    标签: python matrix scipy


    【解决方案1】:

    真的不知道你在这里尝试什么:

    for k, v in term_dict.items():
            r = int(k[0][1:])
            c = int(k[1][1:])
    

    如果你有一个字典,比如说

    d = dict()
    d[(1,2)] = 2.3232
    d[(2,2)] = 12.3232
    
    for k, v in d.items():
      #here k is (1,2)
      #k[0] == 1
      #k[0][1:] == 1[1:] 
    

    您正在尝试从 int 类型中分割某些内容。您的预期结果是什么?

    试试

    for k, v in term_dict.items():
            r = int(k[0])
            c = int(k[1])
    

    改为

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      相关资源
      最近更新 更多