我试图用字典键匹配列表值并打印出来。
问题:打印输出看起来很糟糕。
marbles = {"red": 34, "green": 30, "brown": 31, "yellow": 29 }
myLst=["red","orange"]
for k,v in marbles.items():
for item in myLst:
if item in k:
print('Found',item)
else:
print('Not Found',item)
输出:
Not Found red
Not Found orange
Not Found red
Not Found orange
Found red
Not Found orange
Not Found red
Not Found orange
我用这种方法解决了这个问题:将密钥放在另一个列表中,然后比较2个列表,它们的输出效果很好:
mrblKeyList=[] #empty list to put the keys
for key in marbles.keys():
mrblKeyList.append(key)
print (mrblKeyList)
for item in myLst:
if item in mrblKeyList:
print('Found',item,' in both lists')
else:
print('Did not find',item, 'in both lists')
在第一种方法中,我可以压缩,压缩或其他任何方法吗?预先感谢您的宝贵时间。