第一个列表包含类别,第二个列表包含该类别的项目。
例如:
list1 = {"vehicle", "fruits", "mobile phone", etc.....}
list2 = {"vehicle"=>"toyota", "vehicle"=>"honda", "vehicle"=>"..", "fruits"=>"orange", "fruits"=>"apple", "fruits"=>"...", "mobile phone"=>"nokia", "mobile phone"=>"samsung", "mobile phone"=>"iphone", "mobile phone"=>"...."}
所以如果我以这种格式显示它:
Category 1
-items
-items
-items
-items
Category 2
-items
-items
-items
-items
Category 3
-items
-items
-items
-items
Category n
-items
-items
-items
-items
目前我正在遍历这两个列表,检查属于它的项目是否列出并显示它。是否有更好的方式来显示这些项目和类别?因为如果我要分别显示这些类别,我将不得不循环3次。
这是我的意思的一个例子。
<!--display vehicle-->
for a in list1:
for b in list2:
if a==vehicle && a == b.key:
print(a)
print(b.value)
end if
end for
end for
<!--display fruits-->
for a in list1:
for b in list2:
if a==fruits && a == b.key:
print(a)
print(b.value)
end if
end for
end for
<!--display mobile phone-->
for a in list1:
for b in list2:
if a==mobile phone && a == b.key:
print(a)
print(b.value)
end if
end for
end for
答案 0 :(得分:0)
尝试使用HashTable而不是第二个列表。
通过这种方式,您可以直接访问类别项目,而无需搜索它们。 这使得它成为2个循环,实际上是两个容器中所有项目的1个循环
如果您开发OOP,我建议使用带有类别和项目列表的对象。 而只是创建一个这些对象的列表 - 一个循环。
答案 1 :(得分:0)
恕我直言,只需从内部测试中删除硬编码值即可解决您的问题
<!--display joined -->
for a in list1:
for b in list2:
if a == b.key:
print(a)
print(b.value)
end if
end for
end for
这就是全部