【问题标题】:map array index to dictionnary [closed]将数组索引映射到字典 [关闭]
【发布时间】:2018-12-14 22:16:02
【问题描述】:

我有一个这样的数组:

[[12, 14, 74, 55, 78 ]]

还有一个像这样的字典:

{'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 } 

字典键的值是数组的索引,我想在 Python 3 中得到这个结果:

apple=12
banana=78
ice=55
orange=74
cheese=14

【问题讨论】:

  • 就这样?您确定您没有遗漏不工作的代码并且您知道问题出在哪里并且您正在寻找解决方法:)?
  • 请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask... the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。但是,如果您遵循您在网上找到的任何资源,进行诚实的编码尝试并遇到问题,那么您将有一个很好的示例可以发布。

标签: python python-3.x dictionary arraylist


【解决方案1】:

这就是你要找的吗?

first = [[12, 14, 74, 55, 78 ]]

second = {'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 } 

result = {key: first[0][val] for key, val in second.items()}
# {'apple': 12, 'banana': 78, 'ice': 55, 'orange': 74, 'cheese': 14}

【讨论】:

    【解决方案2】:

    那么,是这样的吗?

    >>> l = [[12, 14, 74, 55, 78 ]]
    >>> d = {'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 }
    >>> out = {}
    >>> for k, v in d.items():
    ...    out[k] = l[0][v]
    ...    
    >>> out
    {'apple': 12, 'banana': 78, 'ice': 55, 'orange': 74, 'cheese': 14}
    

    【讨论】:

      【解决方案3】:

      您可以遍历字典并打印所有键以及数组中的相应值:

      somedict = {'apple': 0, 'banana': 4, 'ice': 3, 'orange': 2, 'cheese': 1 }
      somearray = [12, 14, 74, 55, 78]
      for k, v in somedict.items():
          print(k + '=' + str(somearray[v]))
      

      【讨论】:

        猜你喜欢
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        • 2023-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        相关资源
        最近更新 更多