简体   繁体   English

在python中以字符串形式访问列表中的列表名称

[英]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. 注意:some_var是我从其他函数获取的变量,它工作正常。

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. 在这段代码中,我无法以字符串形式访问IP_list的元素,因为它的元素是列表本身。 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. 我想以字符串形式访问IP_list的3个元素,以便可以对其进行解析,然后与先前提取的名为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: 但是,您可以切换到字典结构,并将所需的名称存储为Key然后为其分配一个列表,如下所示:

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)

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

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