将项目列表与python中的字典进行比较

时间:2018-03-31 16:50:06

标签: python

my_dict = {'one': 1, 'two': 2, 'three': 3}
my_keys = ['three', 'one','ten','one']

solutions = []
for key,value in my_dict.items():
    found = False
    for i in my_keys:
        if i in key:
           solutions.append(value)
           found = True
           break
        if not found:
           solutions.append('Nan')

我得到了这个输出:

  

['Nan',1,'Nan','Nan','Nan','Nan',3]

预期输出为:

  

输出:['3','1','Nan','1']

如何获得预期的输出?

2 个答案:

答案 0 :(得分:3)

使用list comprehensiondict.get(),可以这样做:

代码:

solutions = [my_dict.get(k, 'Nan') for k in my_keys]

测试代码:

my_dict = {'one': 1, 'two': 2, 'three': 3}
my_keys = ['three', 'one', 'ten', 'one']

solutions = [my_dict.get(k, 'Nan') for k in my_keys]
print(solutions)

结果:

[3, 1, 'Nan', 1]

答案 1 :(得分:1)

您似乎想要生成与my_keys列表相关的解决方案列表。

试试这个:

ocation / {
  set $memcached_key "$uri?$args";
  memcached_pass memcached.up;
  memcached_gzip_flag 2; #  net.spy.memcached use second byte for compression flag
  default_type text/html;
  charset utf-8;
  gunzip on;
  proxy_set_header Accept-Encoding "gzip";
  error_page  404 405 400 500 502 503 504 = @fallback;
}
相关问题