假设我创建了一个字典并存储了以下键和值:
bod = {“Test1”:12345,“Test2”:1323242,...}
现在,如果我创建一个新列表并具有以下值
bof = [“Test3”,“Test1”,“Test4”,“Test2”]
是否可以使用dict变量作为调用将其与列表匹配,并使用以下代码(伪)
在新变量内分配匹配键的值for l in bof:
newbof = line.split()
try:
newvalues = bod[values]
print newvalues
答案 0 :(得分:3)
>>> bod = { "Test1" : 12345, "Test2" : 1323242 }
>>> bof = ["Test3", "Test1", "Test4", "Test2"]
>>> [bod.get(x) for x in bof]
[None, 12345, None, 1323242]
其他变体
>>> [bod.get(x, 0) for x in bof]
[0, 12345, 0, 1323242]
>>> [bod[x] for x in bof if x in bod]
[12345, 1323242]
答案 1 :(得分:0)
根据我的理解,无法完全理解您的问题,
newvalues=[]
for i in bof:
if bod.get(i):
newvalues.append(bod[i])
print newvalues
优化
newvalues=[bod[i] for i in bof if bod.get(i)]
答案 2 :(得分:0)
据我所知:
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