简体   繁体   English

如何在 Python 中打印数组的名称?

[英]How do I print name of array in 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 .现在我想在打印中能够调用XYZ数组而不是my_array So I don't have to change it twice, but It will show the same output.所以我不必更改它两次,但它会显示相同的输出。

How do I that?我该怎么做?

To print an array in Python, use the print() function.要在 Python 中打印数组,请使用 print() 函数。 The print() is a built-in Python function that takes the name of the array containing the values and prints it. print() 是一个内置的 Python 函数,它获取包含值的数组的名称并打印它。 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.要在 Python 中创建一个数组,请使用 numpy 库并使用 np.array() 函数创建一个数组,然后在控制台中打印该数组。

import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr)将 numpy 导入为 np arr = np.array([1, 2, 3, 4, 5]) print(arr)

you can use a class to store the array and the name, then you can access with .name o .array您可以使用一个类来存储数组和名称,然后您可以使用 .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)

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM