How do I print name of array in Python? - python

I have few arrays, in my code. I wanna be able to change, which I am using in one place, and to be able to print name of it only changing one line (definition).
Example:
XYZ=my_array #definition of which array I am using now I am calling only XYZ
#some_code
print('the name of array I am using is my_array')
Now I want to have in print being to able call XYZ array not my_array. So I don't have to change it twice, but It will show the same output.
How do I that?

you can use a class to store the array and the name, then you can access with
.name o .array
class Foo():
def __init__(self, array, name):
self.array = array
self.name = name
my_array = [1,2,3,4]
XYZ=Foo(my_array, "name")
print(XYZ.array)
print(XYZ.name)

To print an array in Python, use the print() function. The print() is a built-in Python function that takes the name of the array containing the values and prints it. To create an array in Python, use the numpy library and create an array using the np.array() function, and then print that array in the console.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

There are many ways to answer this question.
This is one of the ways that i would do it.
You can store your list in a dict and assign a key(basically a unique name) to it and you can call it at your disposal when u want it.
_my_dict = {
"my_first_array" : [1,2,3],
"my_second_array" : [4,5,6],
}
# this is how to get all the names of the list
print(_my_dict.keys()) # ['my_first_array','my_second_array']
# this is how to access your list by name
print(_my_dict['my_first_array']) # [1,2,3]

Related

Is indexed slice a view

In torch slicing creates a View i.e. the data is not copied into a new tensor i.e. it acts as ALIAS
b = a[3:10, 2:5 ]
My understanding is that is not the case for indexed slice. f.e.
b = a[[1,2,3] : [5,11]]
Is this correct ?
And second is there a module that mimic a view i.e. internally holds the indexes but access the original tensor i.e. act as a sort of proxy ?
Something like this, but more general :
class IXView:
def __init__(self, ixs, ten):
self.ixs = ixs
self.ten = ten
def __getitem__(self, rows) :
return self.ten[self.ixs[rows],:]
You are correct that iterable-indexed tensor slices do not create a view but rather create a new copy in memory. It seems in practice that this is because any tensor view operation that creates non-contiguous tensor data then calls output.contiguous() under the hood. The one exception seems to be torch.view. More on this here.. You can see this for yourself by calling is_contiguous() or <tensor>.storage().data_ptr() to view the memory address.
a = torch.rand([10,10,10])
a.is_contiguous()
>>> True
a.storage().data_ptr()
>>> 93837543268480 # will be different for you
### normal torch slicing
b = a[3:4,2:8,5:6]
b.is_contiguous()
>>> False
b.storage().data_ptr()
>>> 93837543268480 # same as for a, because this is a view of the data in a
### List slicing of a tensor
c = a[[1,2,3],[2,3,4],:]
c.is_contiguous()
>>> True
c.storage().data_ptr()
>>> 93839531853056 # different than a

How would I interact with an object with no name?

How would I go about interacting with an instance of a class that isn't created directly by me, similar to below:
Matrix = [[MyClass() for x in range(5)] for y in range(5)]
I'm attempting to read some information from each instance at each index of the Matrix, such a number like anyNum = 9. How would I go about doing this since I didn't assign a name to each instance?
You have a list of lists, so simply iterate:
for my_list in Matrix:
for obj in my_list:
do_something(obj)
Here, obj is an instance of MyClass.
You can access the object via indexing:
anyNum = Matrix[0][0]

How to include an array as a parameter of an object in python?

So I know how to create objects in python with things like strings and numbers as parameters, but how would I include an array as one of the parameters of an object I want to create?
It's the same process as with the all other attributes. Asign the attributes via def __init__() function and that's it. For example:
class EvenNumbers:
def __init__(self, array):
self.evenNumbers = array
Create an object:
array = [2, 6, 4] #NOTE: this structure is type list not array
en = EvenNumbers(array)
And then use it for whatever you need.

Print content and several attributes of a numpy array to a text file

I have an array. My task is to print out the array, along with its shape, size, item size, dimensions, and data type name. The output should be a text file - each attribute should be on a new line.
When I attempt to use the following code, I get the error:
File "<ipython-input-76-f4d4f45285be>", line 1, in <module>
print(a.shape)
AttributeError: 'NoneType' object has no attribute 'shape'
I have tried two options, open a text file and np.savetxt. Neither seems to work.
Here is the code:
import numpy as np
a = np.arange(15).reshape(3,5)
a = print(a)
shape = print(a.shape)
size = print(a.size)
itemsize = print(a.itemsize)
ndim = print(a.ndim)
dtype = print(type(a.dtype))
with open("demo_numpy.tx","w") as text:
text.write(a,shape,size,itemsize,ndim,dtype, file = text)
np.savetxt('demo_numpy.txt',[a,shape,size,itemsize,ndim,dtype])
What am I doing wrong, and how can I fix my output?
print just prints the value passed in to stdout and returns None. If you want to access a property just do it without print:
import numpy as np
a = np.arange(15).reshape(3,5)
shape = a.shape
size = a.size
itemsize = a.itemsize
ndim = a.ndim
dtype = a.dtype
And if you want to print don't assign the return value of print:
print(a)
print(a.shape)
print(a.size)
print(a.itemsize)
print(a.ndim)
print(a.dtype)
Note that you don't correctly write to files, in the first case you can only write one argument at a time, you need to either str.join them or do multiple text.writes. In the second case you should check the documentation of numpy.savetxt - it expects an array as second argument not a list of several attributes.
For example:
with open("demo_numpy.tx","w") as text:
text.write(str(a))
text.write(str(shape))
text.write(str(size))
text.write(str(itemsize))
text.write(str(ndim))
text.write(str(dtype))
# or:
# text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])))
np.savetxt('demo_numpy.txt', a)
I'd like to use something like this:
# import numpy as np
# my_array = np.arange(3)
metadata = [(method, getattr(my_array, method)) for method in dir(my_array) if (not callable(getattr(my_array, method))) and (not method.startswith('__'))]
names, values = zip(*metadata) # 2 lists
Then loop over names & values and write into a file.

Is there a way in Python to return a value via an output parameter?

Some languages have the feature to return values using parameters also like C#.
Let’s take a look at an example:
class OutClass
{
static void OutMethod(out int age)
{
age = 26;
}
static void Main()
{
int value;
OutMethod(out value);
// value is now 26
}
}
So is there anything similar in Python to get a value using parameter, too?
Python can return a tuple of multiple items:
def func():
return 1,2,3
a,b,c = func()
But you can also pass a mutable parameter, and return values via mutation of the object as well:
def func(a):
a.append(1)
a.append(2)
a.append(3)
L=[]
func(L)
print(L) # [1,2,3]
You mean like passing by reference?
For Python object the default is to pass by reference. However, I don't think you can change the reference in Python (otherwise it won't affect the original object).
For example:
def addToList(theList): # yes, the caller's list can be appended
theList.append(3)
theList.append(4)
def addToNewList(theList): # no, the caller's list cannot be reassigned
theList = list()
theList.append(5)
theList.append(6)
myList = list()
myList.append(1)
myList.append(2)
addToList(myList)
print(myList) # [1, 2, 3, 4]
addToNewList(myList)
print(myList) # [1, 2, 3, 4]
Pass a list or something like that and put the return value in there.
In addition, if you feel like reading some code, I think that pywin32 has a way to handle output parameters.
In the Windows API it's common practice to rely heavily on output parameters, so I figure they must have dealt with it in some way.
You can do that with mutable objects, but in most cases it does not make sense because you can return multiple values (or a dictionary if you want to change a function's return value without breaking existing calls to it).
I can only think of one case where you might need it - that is threading, or more exactly, passing a value between threads.
def outer():
class ReturnValue:
val = None
ret = ReturnValue()
def t():
# ret = 5 won't work obviously because that will set
# the local name "ret" in the "t" function. But you
# can change the attributes of "ret":
ret.val = 5
threading.Thread(target = t).start()
# Later, you can get the return value out of "ret.val" in the outer function
Adding to Tark-Tolonen's answer:
Please absolutely avoid altering the object reference of the output argument in your function, otherwise the output argument won't work. For instance, I wish to pass an ndarray into a function my_fun and modify it
def my_fun(out_arr)
out_arr = np.ones_like(out_arr)
print(out_arr) # prints 1, 1, 1, ......
print(id(out_arr))
a = np.zeros(100)
my_fun(a)
print(a) # prints 0, 0, 0, ....
print(id(a))
After calling my_fun, array a stills remains all zeros since the function np.ones_like returns a reference to another array full of ones and assigns it to out_arr instead of modifying the object reference passed by out_arr directly. Running this code you will find that two print(id()) gives different memory locations.
Also, beware of the array operators from numpy, they usually returns a reference to another array if you write something like this
def my_fun(arr_a, arr_b, out_arr)
out_arr = arr_a - arr_b
Using the - and = operator might cause similar problems. To prevent having out_arr's memory location altered, you can use the numpy functions that does the exactly same operations but has a out parameter built in. The proceeding code should be rewritten as
def my_fun(arr_a, arr_b, out_arr):
np.subtract(arr_a, arr_b, out = out_arr)
And the memory location of out_arr remains the same before and after calling my_fun while its values gets modified successfully.

Categories