【发布时间】:2016-07-23 13:23:18
【问题描述】:
我有一个整数列表(标签)。我想将列表项映射到字典(类)的值项并获取相应的字典键作为输出。
我正在使用:
h = classes.items()
for x in tags:
for e in h:
# print x, e, # uncomment this line to make a diagnosis
if x == e[1]:
print e[0]
else:
print "No Match"
Classes 是字典。
Tags 是包含我想与类映射的项目的列表。当我运行这段代码时,我在输出中得到了 2616 次 No Match。
2616 = 8 (no. of tuples)*327 (no. of items of tags list)
【问题讨论】:
-
尝试在 if 语句之前添加一行 print x,e。这将帮助您了解比较不起作用的原因。您可能希望在此处分享您的输出摘录以获得帮助。
-
你能发布
class.items()和tags的样本吗? -
@gauden 先生,我得到了:liverpool@gandalf:~/rise/rise$ python test.py 7 Traceback(最近一次调用最后):文件“test.py”,第 57 行,在 print x, e NameError: name 'e' is not defined 这是有道理的,因为变量 e 是在第二个 'for' 循环内启动的。
-
您真的想将标签映射到字典键并将其存储到某个对象,还是只想打印它们?
-
@IronFist 示例数据:class.items() = [('Ford', 1), ('Nissan', 0), ('Mazda', 4), ('Ferrari', 2 ), ('Suzuki', 3), ('Honda', 5), ('Toyota', 6), ('Tesla', 7)] tags = ['0','2','1',' 3','4','7','2','0','1','6','3','2','8','4','1','2' ,'0','7','5','4','1']
标签: python list loops dictionary