0

假设我创建了一个字典并存储了以下键和值:

bod = {“Test1”:12345,“Test2”:1323242,...}

现在,如果我创建一个新列表并具有以下值

bof = [“Test3”、“Test1”、“Test4”、“Test2”]

是否可以使用 dict 变量作为调用以将其与列表匹配并使用以下代码(伪)在新变量中分配匹配键的值

for l in bof:
    newbof = line.split()
      try:
        newvalues = bod[values]
        print newvalues
4

3 回答 3

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]
于 2012-10-17T06:09:39.480 回答
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)]
于 2012-10-17T06:10:56.910 回答
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]

另请注意,虽然 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
于 2012-10-17T06:12:08.527 回答