[英]create 2d array in python?
这是我试图创建2d矩阵的代码
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'] ]
附加所有值,列表具有相同的值。 我怎么能避免这个?
您在列表上使用*
,它有一个陷阱 - 它将列出对同一对象的大量引用。 这对于像int
或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是多范式的!)
另外一点,你的代码并不好。 Python中的for
循环旨在处理对象的迭代,这样您就不必手动管理索引变量(代码中的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
定义为一tagProb
的numpy数组(具有大量线性代数函数的快速基于C的数组类型),其中所有值都在一行中。 第二行将它强制转换为高度m+1
和推断宽度的矩阵(注意它必须是正方形才能工作;如果需要,你可以用None
填充它)然后转置它。 我相信这是你的迭代所做的,但它有点难以理解 - 让我知道你是否想要这样做。
一次创建一个列表并插入它们:
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
被添加到,然后对每一行,它增加了列表中列出的名单。 (尽管如此,您可能希望进行列表复制)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.