Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filling an array with a loop in python

Tags:

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

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

like image 264
Cross Man Avatar asked May 26 '15 12:05

Cross Man


People also ask

How do you fill an array in for loop in Python?

Fill Array With Value With the for Loop in Pythonempty() function by specifying the shape of the array as an input parameter to the numpy. empty() function. We can then allocate the desired value to each index of the array by using a for loop to iterate through each array element.

How do you populate an empty array in Python?

In python, we don't have built-in support for the array, but python lists can be used. Create a list [0] and multiply it by number and then we will get an empty array.

How do you populate a list in Python?

Python provides a method called . append() that you can use to add items to the end of a given list. This method is widely used either to add a single item to the end of a list or to populate a list using a for loop.

How do you make a loop list?

Using for Loops You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.


1 Answers

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']]
like image 79
ZdaR Avatar answered Sep 25 '22 17:09

ZdaR