【问题标题】:Compare list of items to dictionary in python [duplicate]将项目列表与python中的字典进行比较[重复]
【发布时间】:2018-09-10 10:12:52
【问题描述】:
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')

我得到这个输出:

['南', 1, '南', '南', '南', '南', 3]

预期的输出是:

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

我怎样才能得到预期的输出?

【问题讨论】:

    标签: python


    【解决方案1】:

    您似乎想针对 my_keys 列表生成解决方案列表。

    试试这个:

    my_dict = {'one': 1, 'two': 2, 'three': 3}
    my_keys = ['three', 'one','ten','one']
    
    solutions = []
    for key in my_keys:
        if key in my_dict:
            solutions.append(my_dict[key])
        else:
            solutions.append('Nan')
    
    print(solutions)
    

    【讨论】:

      【解决方案2】:

      使用 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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 1970-01-01
        • 2019-03-24
        • 2017-06-21
        • 2020-11-07
        相关资源
        最近更新 更多