Home > Mobile >  Returning list element name instead of its tuple in a nested list
Returning list element name instead of its tuple in a nested list

Time:10-19

I'm working with a nested list that contains the following elements:

A_list = ("A1","A2","A3")
B_list = ("B1","B2","B3")
Nested_List= [A_list,B_list]

def list_sort(input_value,m_list):
    m = 0
    for x in m_list:
        for y in m_list[m]:
            if input_value == y:
                print(m_list[m],",", y)
                      
        m  = 1

input_value = "A2"
list_sort(input_value,Nested_List)

I am using a search algorithm to return the matching string element in and the corresponding sub-list name such as: A_list, A2.

Unfortunately when I do this I get: ('A1','A2','A3'), A2.

Is there anyway to fix this?

CodePudding user response:

A variable's name is not part of its content so you'll need to add that to your data structure. One way of doing it would be to make it a dictionary instead of a list (of lists):

A_list = ("A1","A2","A3")
B_list = ("B1","B2","B3")
Nested_List= {"A_list":A_list, "B_list":B_list}

Then your function could go through the items of the dictionary to perform the search:

def list_sort(input_value,m_list):
    for listName,content in m_list.items():
        if input_value in content:
            print(listName, input_value, sep=", ")

There is a way to get at a variable name from its content but it is not reliable and definitely not something you should use in real life:

def list_sort(input_value,m_list,context=locals()):
    m = 0
    for x in m_list:
        for y in m_list[m]:
            if input_value == y:
                listName = next(n for n,c in context.items() if id(c) == id(x))
                print(listName,",", y)
                      
        m  = 1

CodePudding user response:

I fixed the issue using a dictionary:

A_list = ("A1","A2","A3")
B_list = ("B1","B2","B3")
Nested_List= [A_list,B_list]
List_Dict = {("A1","A2","A3"):"A_list",("B1","B2","B3"):"B_list"}


def list_sort(input_value,m_list):
    m = 0
    for x in m_list:
        for y in m_list[m]:
            if input_value == y:
                print(List_Dict[m_list[m]],",", y)
                      
        m  = 1

input_value = "A2"

list_sort(input_value,Nested_List)
  • Related