据我所理解:
In [325]: bod = { "Test1" : 12345, "Test2" : 1323242}
In [326]: bof = ["Test3", "Test1", "Test4", "Test2"]
In [327]: [bod[i ]for i in bof if i in bod]
Out[327]: [12345, 1323242]
或者,如果您想将值保留在 bod 中:
In [332]: [bod[x] if x in bod else x for x in bof]
Out[332]: ['Test3', 12345, 'Test4', 1323242]
或者
[bod.get(x,x) for x in bof]
Out[333]: ['Test3', 12345, 'Test4', 1323242]
另请注意,虽然 usingget
更简洁,但 usingin
更快:
In [337]: % timeit [bod[x] if x in bod else x for x in bof]
1000000 loops, best of 3: 1.39 us per loop
In [338]: % timeit [bod.get(x,x) for x in bof]
100000 loops, best of 3: 1.88 us per loop