简体   繁体   English

在python中用循环填充数组

[英]filling an array with a loop in python

my problem is as follows, i have an array named crave=['word1','word2','word3'....'wordx'] and i want to transform into ITEM=[['word1','word2','word3'],['word4','word5','word6'] etc] i used the following code 我的问题如下,我有一个名为crave=['word1','word2','word3'....'wordx'] ,我想转换成ITEM=[['word1','word2','word3'],['word4','word5','word6'] etc]我使用下面的代码

buff=[['none','none','none']]
n=10
ITEM=[]
i=0
while 1>0 :


 buff[0][0]=crave[i]
 buff[0][1]=crave[i+1]
 buff[0][2]=crave[i+2]
 ITEM.insert(len(ITEM),buff[0])
 i=i+3
 if i>n:
      break

but what i get instead is [['wordx-2','wordx-1','wordx'],['wordx-2','wordx-1','wordx'],['wordx-2','wordx-1','wordx']etc] why does this happen ?:( 但我得到的是[['wordx-2','wordx-1','wordx'],['wordx-2','wordx-1','wordx'],['wordx-2','wordx-1','wordx']etc]为什么会发生这种情况?:(

You can easily do this by using list comprehension. 您可以使用列表理解轻松完成此操作。 xrange(0, len(crave), 3) is used to iterate from 0 to len(crave) with an interval of 3. and then we use list slicing crave[i:i+3] to extract the required data. xrange(0, len(crave), 3)用于从0到len(crave)迭代,间隔为3.然后我们使用list slicing crave[i:i+3]来提取所需的数据。

crave=['word1','word2','word3','word4','word5','word6','word7']

ITEM = [crave[i:i+3] for i in xrange(0, len(crave), 3)]

print ITEM
>>> [['word1', 'word2', 'word3'], ['word4', 'word5', 'word6'], ['word7']]

try to this. 试着这个。

crave = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7']
li = []
for x in range(0, len(crave), 3):
    li.append(crave[x:x+3])
print li
import numpy as np
In [10]: a =np.arange(20)

In [11]: a
Out[11]: 
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])

In [12]: np.array_split(a,len(a)/3)
Out[12]: 

[array([0, 1, 2, 3]),
 array([4, 5, 6, 7]),
 array([ 8,  9, 10]),
 array([11, 12, 13]),
 array([14, 15, 16]),
 array([17, 18, 19])]

In respect to the question of "why does this happen": 关于“为什么会发生这种情况”的问题:

The problem is that buff[0] is being referenced by the .insert, not copied. 问题是.insert正在引用buff [0],而不是复制。 Hence on the next turn of the loop when buff changes anything that references buff will also change. 因此在循环的下一个循环中,当buff改变任何引用buff的东西也会改变。

To do an explicit copy use list(). 要做一个显式的副本使用list()。 Eg 例如

 ITEM.insert(len(ITEM),list(buff[0]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM