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)
Related
I am trying to input the 5 numbers in defined length set and try to print out those numbers but it's giving "TypeError: 'int' object is not iterable" this error.
print("enter 5 numbers")
a=set(5)
for i in range(0,5):
a.append(int(input("enter a number")))
for i in range(0,5):
print("numbers in array are",a[i])
I think there is some confusion on what set actually does. I assume you want to make a predefined set of length 5. When doing:
set(5)
you get:
TypeError: 'int' object is not iterable
because you're trying to make a set containing only the integer 5. If you want to make a set from that, you would have to include an iterable, maybe like so:
set((5,))
Out: {5}
But what I would recommend you to do is declare
a = [] # create an empty list
and then run your code. At the end then, I would make a set by typing
a = set(a)
Hopefully that was helpful for you! Have fun coding! :)
You cannot fix the size of set while creating.
a = set(5) is the source of your error.
Also, sets do not have append method. You should use a.add("data") for adding elements to the set.
To ensure that the size of set does not exceed a particular length, you can try something like this
fixed_length = 3
a=set()
for i in range(0,5):
if len(a) == fixed_length:
break
else:
a.add(int(input("enter a number")))
for index, element in enumerate(a):
print("numbers in array are", element)
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
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?
I have an array with 20 values, but value 16 is incorrent and must be replaced with the correct value. How can I do that?
texture[16] = 'sky13.jpg'
That code does not work for some reason. The error is "'tuple' object does not support item assignment"
You're working with a tuple instead of a list. Convert it to a list first
texture = list(texture)
texture[16] = 'sky13.jpg
check what texture is
type(texture)
if it is tuple then convert it to list
textute = list(texture)
in python simple way to talk tuple object is immutable list object
more about differences is here What's the difference between lists and tuples?
Tuples in Python are **inmutable**, which means that you can't change the value once you assign it!
You need to convert the tuple to a list:
listOfTextures = list(texture)
And then you will be able to change the values you want to.
I got an error message from my code which says TypeError: 'int' object is unsubscriptable. After doing some research, I understand what it means, but I can't understand why there is a problem.
I narrowed the problem down to this code:
def calcNextPos(models, xcel): # and other irrelevant parameters
for i in range(len(models)):
for j in range(3):
a = xcel[i[j]]*0.5*dt*dt
# More code after this...
I verified that xcel is a list of lists of integers when the function is called, and the indexes should not be out of bounds.
What is going wrong? How can I fix it?
xcel is a two-dimensional list. The correct syntax to access the jth element of the ith sub-list is xcel[i][j], not xcel[i[j]]. The latter attempts to get the jth element of the integer i, which leads to the error described.
In the code for i in range(len(models)):, i is an integer. That makes a loop for values of i between 0 and a less than the length of models.
In the next two lines of the code, i[j] is used to access an array element, which doesn't work. Did you perhaps mean models[j] instead of i[j], like so?
for i in range(len(models)):
for j in range(3):
a = xcel[models[j]]*0.5*dt*dt
# More code after this...