简体   繁体   English

在python中打印索引名称

[英]print index name in python

I want to know how to output the name, not the values, of each index (and sub-index) in a list and in sub-lists. 我想知道如何在列表和子列表中输出每个索引(和子索引)的名称而不是值。

For example, let's say I have a main list, which has 3 other lists each containing 5 sub-lists. 例如,假设我有一个主列表,其中有3个其他列表,每个列表包含5个子列表。 Here is a small example to clarify: 这是一个小例子来澄清:

List1 = [SubList1, SubList2, SubList3, SubList4, SubList5]
List2 = [Apple, Banana, Orange, Pear, Grape]
List3 = [Red, Yellow, Orange, Green, Purple]


Lists = [List1, List2, List3]

MainList = [Lists]

How can I print out 'List1'? 如何打印出“List1”?

When I type in 当我输入

MainList[0][0]

it outputs 它输出

[SubList1, SubList2, ..., Sublist5]

I want the actual name of the index, not its values. 我想要索引的实际名称,而不是它的值。

I thought about using dictionary keys, but the report generator that I am using for the XML conversion outputs all the data into lists. 我考虑过使用字典键,但是我用于XML转换的报表生成器将所有数据输出到列表中。 Does this mean I have no choice but to modify my report generator script to output the data into dictionaries? 这是否意味着我别无选择,只能修改报表生成器脚本以将数据输出到词典中?

Try to use dict() for that purpose: 尝试使用dict()来实现此目的:

List1 = ['SubList1', 'SubList2', 'SubList3', 'SubList4', 'SubList5']
List2 = ['Apple', 'Banana', 'Orange', 'Pear', 'Grape']
List3 = ['Red', 'Yellow', 'Orange', 'Green', 'Purple']


xd = {'List1': List1, 'List2': List2, 'List3': List3}

print xd['List1']

for k, v in xd.iteritems():
    if v == List1:
        print k

>>> ['SubList1', 'SubList2', 'SubList3', 'SubList4', 'SubList5']
>>> List1

You seem to misunderstand. 你好像误解了。 List1 in your example is a variable name. 示例中的List1是变量名称。 It is not stored in the Lists array, only its value is stored. 它不存储在Lists数组中,只存储其值。 So you are not going to get List1 out of Lists. 因此,您不会从列表中获取List1。 Array indexes are integers and the index of List1 in Lists is 0. As the other commenter suggested you might want to convert your Lists structure into a dict. 数组索引是整数,列表中List1的索引是0.正如另一位评论者建议您可能希望将列表结构转换为字典。

Lists = {}
Lists['List1'] = [SubList1, SubList2, SubList3, SubList4, SubList5]
Lists['List2'] = [Apple, Banana, Orange, Pear, Grape]
Lists['List3'] = [Red, Yellow, Orange, Green, Purple]

print(Lists.keys())

list object has no name attributes, you should use pandas.Series as follow: list对象没有名称属性,你应该使用pandas.Series如下:

import pandas as pds
List1 = pds.Series([SubList1, SubList2, SubList3, SubList4, SubList5],name='List1')
List2 = pds.Series([Apple, Banana, Orange, Pear, Grape],name='List2')

you find the name like this: 你找到这样的名字:

print List1.name,List2.name

A list of list become a pandas.DataFrame: 列表列表成为pandas.DataFrame:

Lists = pds.DataFrame([List1, List2, List3])

To answer your question, you should proceed as follow: 要回答您的问题,请按以下步骤操作:

-each sublist become a series - 每个子列表成为一个系列

Sublist = pds.Series([...],name='Sublist')

-each list become a dataframe: - 每个列表成为一个数据帧:

List = pds.DataFrame([Sublist1,Sublist2,..])

-"the" Lists become a dict: - “the”列表成为一个词典:

Lists = {'List1' : List1,
         'List2' : List2,
         ...
         }

-you get the name: 你得到的名字:

for name_list,list in Lists.items(): 
     name_list,list.columns

Quick solution: 快速解决方案

class NamedList(list):
    __slots__ = ['__name__'] # optimisation, can be ommited
    def __init__(self, name, *args):
        super().__init__(*args)
        self.__name__ = name
    def __repr__(self):
        return "%s(%r, %s)" % (type(self).__name__, self.__name__, super().__repr__())

test = NamedList('test', [1, 2, 3])
print(test)
print(test.__name__)

Output: 输出:

NamedList('test', [1, 2, 3])
test

If your lists always are stored as variables, you can retrieve their names by using some sort of identity dict (sadly there is none in standard library): 如果您的列表始终存储为变量,则可以使用某种标识dict检索其名称(遗憾的是标准库中没有):

names = IdentityWeakKeyDict((obj, name for name, obj in locals().items()))

names should now map objects to their names. names现在应该将对象映射到它们的名称。

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

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