获取列表名称 [英] Get the name of a list

查看:94
本文介绍了获取列表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是否可以通过简单的方式实现,但是我正在尝试获取列表对象的名称.

I am not sure if this is possible in a simple way, but I am trying to get a name of a list object.

我确实尝试过__name__,但是由于列表对象没有属性__name__

I did try with __name__ but I get an error because the list object does not have an attribute __name__

甚至可以获取列表的变量名称,而无需子类化列表对象并添加__name__属性?

Is even possible to get the variable name for a list, without subclass the list object and add the __name__ attribute?

编辑 这与建议的副本无关.

EDIT This has nothing to do with the suggested duplicate.

这是我的情况:

cucumbers=[]
oranges=[]
salads=[]
...
masterlist=[cucumbers, oranges, salads]

有时我只得到2个列表,而其他时候我得到5个,因此,主列表每次都具有不同数量的列表.当我打印它时,我只得到值;所以我不知道第一名单是黄瓜,橙子,沙拉还是其他.

At times I just get 2 lists, otehr times I get 5, so the masterlist has different number of lists in it, every time; and when I print it, I get only the values; so I don't know if the first list is cucumbers, oranges, salads or whatever it is.

我正在尝试查询列表,以便可以获取variable name,而不是对象的类型.因此print masterlist[1].name会给我黄瓜"或与该列表相关的名称.

I am trying to query the list so I can get the variable name, not the type of the object. so print masterlist[1].name will give me "cucumbers" or whatever is the name associated to that list.

推荐答案

您可以简单地使用字典:

You could simply use a dictionary instead:

masterdict={'cucumbers': cucumbers, 'oranges': oranges, 'salads': salads}

而不是检查名称,而是遍历字典的各项:

And instead of checking the name you iterate over the items of the dictionary:

for name, sublist in masterdict.items():
    print(name, sublist)

如果您希望将其订购(并且您没有Python 3.6,其中订购了dict)则为collections.OrderedDict.

In case you want it ordered (and you don't have Python 3.6 where dicts are ordered) there is collections.OrderedDict.

获取变量名称的问题是变量引用了python对象,但是可以有很多(以不同的名称命名)引用同一对象的变量.同样,对象不需要(可见)名称就可以存在.例如,如果您有类似的东西:

The problem with getting the name for a variable is that variables reference python objects, but there can be many (differently named) variables referencing the same object. Also an object doesn't need a (visible) name to exist. For example if you have something like:

def func():
    cucumber = [1, 2, 3]
    return [cucumber]

然后,函数完成时,名称cucumber不再存在.但是对象([1, 2, 3]列表)仍然存在,但是由于它包装在另一个列表中,因此它甚至不再具有名称".当返回值存储在变量中时,只有外部列表可以有名称.

Then the name cucumber doesn't exist anymore when the function finished. But the object (the [1, 2, 3] list) is still existing, but because it was wrapped in another list it's doesn't even have a "name" anymore. Just the outer list could have a name when the returned value was stored in a variable.

这篇关于获取列表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆