代码之家  ›  专栏  ›  技术社区  ›  harshit

在python中创建二维数组?

  •  2
  • harshit  · 技术社区  · 15 年前

    这是我试图创建二维矩阵的代码

    m=4
    tagProb=[[]]*(m+1)
    count=0
    index=0
    for line in lines:
        print(line)
        if(count < m+1):
           tagProb[index].append(line.split('@@')[2].strip()) 
           count+=1
        if(count == m+1): // this check to goto next index
            count = 0
            index+=1
    print(tagProb)  
    

    我得到了O/P

    [['0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', '0.0', '0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', 0.0'], ['0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', .0', '0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', '0.0'], '0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', '0.0','0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', '0.0'] ]
    

    所有值都将被附加,并且列表具有相同的值。 我怎样才能避免这个?

    3 回复  |  直到 15 年前
        1
  •  10
  •   Katriel    15 年前

    你正在使用 * 在列表上,它有一个gotcha——它将列出大量引用 相同的 对象。这对像 int S或 tuple list ,因为更改其中一个对象将更改所有对象。见:

    >>> foo = [[]]*10
    >>> foo[0].append(1)
    >>> foo
    [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
    

    如果不希望发生这种情况,避免这种情况的标准方法是使用列表理解,它将用新对象初始化列表:

    >>> bar = [[] for _ in range(10)]
    >>> bar[0].append(1)
    >>> bar
    [[1], [], [], [], [], [], [], [], [], []]
    

    然而,这个问题在惯用的python中并没有出现太多,因为初始化一个大的列表并不是一件常见的事情——这是一种非常C的心态。(这并不是说有时候这不是正确的做法——Python是多范式!)

    另一方面,您的代码不好。这个 for python中的循环设计用于处理对象的迭代,这样就不必管理索引变量。( index count 在您的代码中)。最好重写如下:

    import numpy as np
    m = 4
    tagProb = np.array(list(line.split("@@")[2].strip() for line in lines)))
    tagProb = tagProb.reshape((m+1,-1)).T
    

    说明:第一行定义 tagProb 作为一个一维的numpy数组(一种快速的基于C的数组类型,具有许多线性代数函数),所有值都在一行中。第二行将其强制为高度矩阵 m+1 和推断的宽度(请注意,它必须是正方形才能工作;您可以用 None 如有必要),然后将其转置。我相信这就是你的迭代所做的,但这有点难以理解——如果你想帮忙的话,请告诉我。

        2
  •  1
  •   JoshD    15 年前

    一次创建一个列表并插入它们:

    import copy
    m=4
    tagProb=[]
    count=0
    index=0
    for line in lines:
        print(line)
        innerlist = []
        if(count < m+1):
           innerlist.append(line.split('@@')[2].strip()) 
           count+=1
        if(count == m+1): // this check to goto next index
            count = 0
            index+=1
            tagProb.append(copy.deepcopy(innerlist))
            innerlist = []
    print(tagProb)  
    

    正如你所看到的,有一个 innerlist 它被添加到,然后对于每一行,它将列表添加到列表列表中。(不过,您可能需要一份列表副本)。

        3
  •  0
  •   harshit    15 年前
    m=4
    tagProb=[]
    count=0
    index=0
     innerlist = []
    for line in lines:
    print(line)
    
    if(count < m+1):
       innerlist.append(line.split('@@')[2].strip()) 
       count+=1
    if(count == m+1): // this check to goto next index
        count = 0
        index+=1
        tagProb.append(innerlist)
        innerlist = []
    print(tagProb)