这是我想要做的简化场景。我有两个词典:
dictA = {"apple": 1, "orange": 2, "chocolate": 3, "mango": 4}
dictB = {"man": "abc", "or": "asdf", "app": "fasdfkl"}
如何进行打印(三个键的实际顺序+值无关紧要):
I can find...
orange2
mango4
apple1
I cannot find...
chocolate3
我曾尝试做过类似的事情,但却陷入了第二部分。
print "I can find ..."
for itemA in dictA:
for itemB in dictB:
if itemA.startswith(itemB):
print itemA + str(dictA[itemA])
会打印
I can find ...
orange2
mango4
apple1
答案 0 :(得分:4)
首先将第一个循环简化为此
print "I can find ..."
for itemA in dictA:
if any(itemA.startswith(itemB) for itemB in dictB):
print itemA + str(dictA[itemA])
第二个循环将使用if not any(...)
这不是一个非常有效的算法,但我想你只是在做练习
答案 1 :(得分:0)
我会跟踪你找到的钥匙并输出你最后找不到的钥匙:
dictA = {"apple": 1, "orange": 2, "chocolate": 3, "mango": 4}
dictB = {"man": "abc", "or": "asdf", "app": "fasdfkl"}
found_keys = set()
for key_b in dictB.keys():
for key_a in dictA.keys():
if key_a.startswith(key_b):
print "I can find: %s %s" % (key_a, dictA[key_a])
found_keys.add(key_a)
break
print "I couldn't find: %s" % dict((k, dictA[k]) for k in set(dictA.keys()) - found_keys)
输出:
I can find: apple 1
I can find: orange 2
I can find: mango 4
I couldn't find: {'chocolate': 3}
编辑:我刚看到gnibbler的answer。我比它更喜欢它,虽然因为我没有使用any
并显式调用dict对象的keys()
方法,所以它可能更容易理解(但是, ,如果你得到了gnibbler的回答,那就去那个)