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 ?:(
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.
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.
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.
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.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With