5

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

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 ?:(

3
  • so you want to split the list into 3 elements sublists? is ther ordering important? Commented May 26, 2015 at 12:58
  • 1
    I tried to understand what your code does, I had to change some lines as to get it compile and run. Here's what I made of it: ideone.com/bHuDx2 Commented May 26, 2015 at 13:48
  • Yes ordering is important Moj Commented May 26, 2015 at 14:06

4 Answers 4

10

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.

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']]
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, especially the processing of the last ("broken") triple - it really works :-) ideone.com/S9AQF7
Thanks for appreciation @Wolf
4

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

1 Comment

...list comprehension explained ;-)
1
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])]

Comments

1

In respect to the question of "why does this happen":

The problem is that buff[0] is being referenced by the .insert, not copied. Hence on the next turn of the loop when buff changes anything that references buff will also change.

To do an explicit copy use list(). E.g.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.