The 'int' object is unsubscriptable - python

I have searched for nearly an hour online, but can't find anything. But I digress, line 6 keeps on returning TypeError: 'int' object is unsubscriptable. Please help me identify what causes this.
def __reassigner__(allL, currentRow, currentSpace):
changingRow=currentRow+1
newl=[-1]*24
while changingRow<8:
distance = changingRow-currentRow
newl[8:15]=allL[changingRow[0:7]] #Line 6, this one
if newl[currentSpace]==-1:
newl[currentSpace]= currentRow
if newl[currentSpace-distance]==-1:
newl[currentSpace-distance]= currentRow
if newl[currentSpace+distance]==-1:
newl[currentSpace+distance]= currentRow
allL[changingRow[0:7]]=newl[8:15]
changingRow+=1
return(allL)

The variable changingRow is an integer, but you try to slice it with changingRow[0:7]. Since this operation is not allowed on ints, you get the error.
I don't know what your intention was with that line. Maybe allL is a list of lists and you were going for allL[changingRow][0:7]?

changingRow in your code seems to be an integer (I assume that after line saying changingRow=currentRow+1). Unfortunately, in line 6, you try to obtain: changingRow[0:7], which doesn't work, since you're trying to access your integer value as if it was an array.

changingRow is an integer value. changingRow[0:7] would extract the first 7 elements of a list-like ("subscriptable") object, but an int has no such "elements" like the ones in lists and strings have.
What are you trying to achieve with changingRow[0:7]?

changingRow is an integer, you can't take indeces 0-7 from it

You can't access write changingRow[0:7] because changingRow is an integer. If you must access it using slice notation (for the first 8 digits or something) you can do str(changingRow)[0:7], but you probably have a design problem.

Related

How to break a list into couple lists

Assume that I have a list with size=(8,64,1,60,60) and want to break it into (4,2,64,1,60,60) and then sum them up along axis 1. I tried the code below but it raised with error :
'list' object has no attribute 'reshape'.
Please note that I want to keep the predictions as a list and do not want to change it to array.
predictions=list(np.random.randint(5,size=(8,64,1,60,60)))
predictions_sum = predictions.reshape(4,2, *predictions.shape[1:]).sum(axis=1)
You are confusing Python's built-in list type with numpy's array. Try this:
predictions=np.array(np.random.randint(5,size=(8,64,1,60,60)))
predictions_sum = predictions.reshape(4,2, *predictions.shape[1:]).sum(axis=1)

The TypeError in python

I'm trying to make a challenge for one of the courses I'm following. I'm new to programming, but I'm eager to learn.
Can you tell me in detail why this error occurs to me and how do solve it.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
for i in default_names:
default_names[i]=default_names[i][0].upper()
i+=1
if i==len(default_names):
break
print default_names
the error: TypeError: list indices must be integers, not str
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
print default_names
What you are looking for is :
for i,s in enumerate(default_names):
or simple:
for i in range(len(default_names)):
The mistake you are doing is that when you say for i in default_names: notice that i value is a string, not int as you are trying to use.
for i in default_names:
print(i)
Will give :
OUT: Justin
john
Emilee
jim
Ron
Sandra
veronica
Wiskley
So the actual code should be, assuming you are trying to convert each string in list to Upper case :
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
EDIT : The OP wants only First char to be Upper case, and since string are immutable, change of code to :
for i in range(len(default_names)):
default_names[i]=default_names[i][0].upper() + default_names[i][1:]
As you can see in your error: TypeError: list indices must be integers, not str. It's because to access the elements of a list, you have to use the index, which is an integer. Basing on the structure of your code, you might have come from a different language. Python's for loop is different from the other languages. It doesn't increment the variable you made over the loop, but rather it iterates over the elements and passes the value to the variable. I think it would be more suitable to use a while loop with the code you made since you have initialized your i to 0. E.g.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
while i < len(default_names):
default_names[i]=default_names[i].upper() #removed the [0] here
i+=1
#removed the other codes here
print default_names
As you become better in python, you can find more efficient ways to do these kinds of things. The result you wanted could be simply made through
default_names = [name.upper() for name in default_names]
which simply iterates all of the names, makes it upper case and saves it back to default_names

getting TypeError: unsupported operand type(s) for -: 'list' and 'list' while doing Min max normalization in python

I have been working with Python for a couple of months..Now,I have to perform min-max normalization for a column of my dataset(.csv file) for which I get the above mentioned type error..I have tried a lot but it still persists..Correct values are retrieved for min and max functions but the types of the results are list rather than float/integer..
This is the line that causes error
for i in range(num):
normalized[i]=(krr[i]-min(krr)/(max(krr)-min(krr))
where krr is the column retrieved from the dataset.Please help.
I have a function "normal" which does the min-max normalization..
I have taken column values using eval as shown in code
def normal(self,arr,num):
print("------------------->entered Normalisation block----------------->")
for i in range(num):
# trr=eval(str(arr[i]))[0:-31]
self.krr[i]=map(float,eval(str(arr[i]))[0:-31]) //extracting one particular column
#mn=min(self.krr)
#mx=max(self.krr)
print(self.krr)
ls=min(self.krr)
hs=max(self.krr)
diff=hs-ls
for i in range(num):
normalized[i]=(self.krr[i]-ls)/diff
OK, so the key issue here is that you are working on a list of sublists, with each sublist containing one number.
If you look at your formula:
(krr[i]-min(krr)/(max(krr)-min(krr))
As you mention, python can deal with the max and min - it will return the sublist that contains the biggest/smallest number. (Though note that getting a list containing one number is very different to getting just the one number) However, subtraction and division between lists is not supported, hence your error message. So sooner or later, you need to get the values out of the sublists.
My recommendation is that immediately after you finish constructing krr, you add the following line to your code:
krr = [element[0] for element in krr]
which converts krr from a list of sublists, to a list of the first element of each sublist.
Edit:
An alternative that I think will work, and is more efficient, is to change
def normal(self,arr,num):
print("------------------->entered Normalisation block----------------->")
for i in range(num):
# trr=eval(str(arr[i]))[0:-31]
self.krr[i]=map(float,eval(str(arr[i]))[0:-31]) # This row
into this:
self.krr[i]=float(eval(str(arr[i]))[0:-31][0])
map applies float to each element of the following list, and creates a new list. Instead, we're asking for the first element of that list, and applying float directly to it. That float is assigned to the index in krr.
PS eval(str(arr[i]))[0:-31] looks rather scary - does eval really need to be invoked here?

How to fix "int" is not subscriptable error?

I keep getting the error 'int' object is not substitutable. I know my problem is within "def filaray()" I also know making "num" a list would be more efficient. However this is an assignment and I'm pretty sure we can only use array's. Is there a way I can fix my error while not making "num" a list?
The line num = random.randint(0,9) sets num to an int, and so when fillaray returns num (assuming size > 0), it is returning an int, not a list, and this int is then passed to totalOdds and totalEvens, which try to subscript it (i.e., do num[i]) as though it were a list, which is an error. Presumably, what you want to do is to append the random ints to the list num instead of overwriting it, e.g., by doing num.append(random.randint(0,9)).

Converting Str to Integer

I get the following error: TypeError: list indices must be integers, not str on this line of code:
a= doc['coordinates']['coordinates']
This is reading records from a db, I would like to know how to convert this into an integer from str?
Thanks
EDIT:
doc['coordinates']['coordinates'] returns coordinate information from a mongoDB, where these are the fields. It returns the relevant information for the first ten times the program runs, then I get this error.
Look at what is happening here:
a= doc['coordinates']['coordinates']
First doc['coordinates'] is evaluated. This returns a list of coordinates, lets say [32.9,23.11].
Now you're trying to look up something in this list with the index 'coordinates'.
a = [32.9,32.11]['coordinates']
This is your list: [32.9,32.11]
Lists only have numerical indices, in this case: 0 and 1.
If you're trying to assign a list of coordinates to a variable, you could just do a = doc['coordinates'] or if you want an individual coordinate, doc['coordinates'][0]

Categories