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]
还要注意,虽然使用get更简洁,但使用in更快:
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
据我所知:
或者如果您想保留bod中没有的值:
或者
还要注意,虽然使用
get
更简洁,但使用in
更快:其他变化
我不能完全理解你的问题
优化了
相关问题 更多 >
编程相关推荐