首页 > 解决方案 > Python - 在嵌套的 for 循环中使用时如何获取列表的名称

问题描述

我在用python 2.6.6

我正在尝试使用一个if语句来检查嵌套 for 循环中的列表名称。

这是我的代码:

blueList = ["light blue", "dark blue"]
redList = ["light red", "dark red"]
orangeList = ["light orange", "dark orange"]

colorsGroup = [blueList, redList, orangeList]

for member in colorsGroup:
    for colorNameInList in member:
        if "orange" in member.__name__:
            print("the name of this list contains the word orange")
        elif "red" in member.__name__:
            print("the name of this list contains the word red")
        elif "orange" in member.__name__:
            print("the name of this list contains the word orange")

我不断得到:

AttributeError: 'list' object has no attribute '__name__'

如果该属性不存在,我可以使用什么来检查列表的名称?

标签: pythonarraysvariablesif-statement

解决方案


如果您希望读取变量名称,请考虑将它们用作字典的键:

colorsGroup = {'blueList':blueList, 'redList':redList, 'orangeList':orangeList}

然后你可以像这样迭代:

for key, value in colorsGroup.iteritems():
    if 'blue' in key:
        print("the name of this list contains....")
    elif 'orange' in key:
        print("the name of this list contains...")
    else:
        print("the name of this list contains...")

推荐阅读