python - 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__'
如果该属性不存在,我可以使用什么来检查列表的名称?
解决方案
如果您希望读取变量名称,请考虑将它们用作字典的键:
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...")
推荐阅读
- asp.net - Asp.net 超链接控件 NavigateURL 属性在 mywebsite 中不起作用
- algorithm - 如何使用合并排序为Scala中的Int列表计算反转计数?
- json - Unity - 从android读取JSON文件
- intellij-idea - Intellij idea - 在结构视图上显示参数名称
- visual-c++ - 在 Visual Studio C++ 上加载大量网格滞后
- spring - 如何使用 Spring Data 进行分页?
- c# - 如何将两个文本框值相乘并在 C# 中显示第三个的答案?
- azure - 错误 ID:VertexFailedFast,错误消息:Vertex 因快速失败错误而失败
- javascript - 我想通过选择类来获取数据并使用 jquery 在控制台中打印它
- intellij-idea - 在 Intellij IDEA 中,如何更改“消息:构建”字体?