简体   繁体   中英

Accessing List name inside a list as a string in python

the code which i am trying is as below -

IP1_list =['abcd', 'efgh']
IP2_list =['asdf', 'zxcv']
IP3_list =['qwer', 'poiu']

IP_list = [IP1_list, IP2_list, IP3_list]

command_list = [cmd1_IP1, cmd2_IP1, cmd3_IP2, cmd4_IP3]

for i in range(len(command_list)):
    command, IP = cpmmand_list[i].split('_',1)
    if some_var == command:
        for j in range(len(IP_list):
            IP_name, unwanted = IP_list[j].split('_',1)
            if IP_name = IP
                "do something" 

Note: some_var is the variable I am getting from some other function, which is working fine.

Here in this piece of code I am not able to access the IP_list's elements as string because the elements of it are the lists itself. for ex: if I execute

print IP_list

It is printing me all the three lists

How to handle this problem? I want to access the IP_list's 3 elements as string, so that I can parse it and then compare with the previously extracted variable named IP.

If any other logic one has then it is welcome. Thanks

You can not get the "name" of the variable as a string, you'll access the object directly and it doesn't have a name per sae. However you could switch to a dictionary structure and store the desired name as a Key and assign one of your lists to it, like so:

IP1_list =['abcd', 'efgh']
IP2_list =['asdf', 'zxcv']
IP3_list =['qwer', 'poiu']

IP_list = {'IP1_list' : IP1_list, 'IP2_list' : IP2_list, 'IP3_list' : IP3_list}


for key in IP_list:
    IP_name, unwanted = key.split('_',1)
        if IP_name == IP:
            "do something"

But then again, I'd do:

IP_list = {'IP1' : IP1_list, 'IP2' : IP2_list, 'IP3' : IP3_list}

and skip

IP_name, unwanted = key.split('_',1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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