【问题标题】:Find all Key-Elements by the different value Value in Dicts通过字典中的不同值 Value 查找所有 Key-Elements
【发布时间】:2017-11-21 18:32:23
【问题描述】:

我有一个两个数组,我想用两个数组创建一个字典,但我面临的问题是我希望重复值应该与列表中的重复值一样多。我正在使用这段代码

text_results = ['hello', 'foo' , 'hi' , 'good' , 'this' , 'hi' ]
scores = [4,2,4,5,1,4]
dictionary = dict(zip(scores,text_result)) 

我希望输出应该是这样的

[(4, 'hello'), (2, 'foo'), (4, 'hi') ,(5, 'good') ,(1, 'this'),(4, 'hi')]

我怎样才能像这样按降序对它进行排序:

[(5, 'good') ,(4, 'hello'),(4, 'hi'), (4, 'hi'), (2, 'foo') ,(1, 'this')]

【问题讨论】:

  • 但那是一个元组列表,而您要求制作字典?请确定你真正想做的是什么。
  • "但我面临的问题是,我希望重复值应该与列表中的重复值一样多。我正在使用这段代码",即这句话我不清楚...
  • 你描述的是一个列表,你可以使用:list(zip(scores,text_results)),或者在Python-2.x中,更简单的zip(scores,text_results)...
  • 意味着重复值应该重复出现在字典中的时间
  • 将 score 作为 dict 的关键似乎没有多大意义。分数不应该是价值吗?

标签: python python-2.7 list sorting dictionary


【解决方案1】:

排序的元组

如果你想要一个排序的元组列表,你可以使用sorted 和相反的顺序对它们进行排序:

print(sorted(zip(scores, text_results), reverse=True))
# [(5, 'good'), (4, 'hi'), (4, 'hi'), (4, 'hello'), (2, 'foo'), (1, 'this')]

值作为列表

如果你真的想要dict,你的值可以是列表。但是,Python dicts 是无序的:

text_results = ['hello', 'foo' , 'hi' , 'good' , 'this' , 'hi' ]
scores = [4,2,4,5,1,4]

table = {}

for name, score in zip(text_results, scores):
    if not table.get(name):
        table[name] = []
    table[name].append(score)

print(table)
# {'this': [1], 'hi': [4, 4], 'foo': [2], 'hello': [4], 'good': [5]}

这样,如果您想要hi 的值,您可以直接获取它们而无需遍历列表:

>>> table.get('hello')
[4]
>>> table.get('hi')
[4, 4]
>>> table.get('not_here')
>>> 

请注意,此功能由collections.defaultdictdefaultdict(list) 提供。不过,我有时会发现额外的输出会分散注意力:

defaultdict(<type 'list'>, {'this': [1], 'hi': [4, 4], 'foo': [2], 'hello': [4], 'good': [5]})

【讨论】:

    【解决方案2】:

    如果你想要这样的输出:[(4, 'hello'), (2, 'foo'), (4, 'hi') ,(5, 'good') ,(1, 'this'),(4, 'hi')]
    那么它不是python含义的字典。 python中的字典使用{}.
    你所说的“字典”是一个列表,每个元素都是一个元组。 所以你应该只创建一个列表,并为你的文本或分数列表的每次迭代添加一个元组:

    if __name__ == "__main__":
        text_results = ['hello', 'foo', 'hi', 'good', 'this', 'hi']
        scores = [4, 2, 4, 5, 1, 4]
        my_own_container = []
        for i in range(len(text_results)):
            my_own_container.append(tuple((scores[i], text_results[i])))
        print(my_own_container)
    

    【讨论】:

    • 如果要按照分数升序排列怎么办?
    • @AliJafar 也许您应该在问题中添加一些工作背景。但我认为 sort 足以解决你的问题。
    【解决方案3】:

    字典只能将一个键映射到一个值。因此,您不能将 this 构造为 vanilla 字典。有一些选择:

    1. 您使用列表(zip(..)list(zip(..))):

      >>> zip(scores,text_results)
      [(4, 'hello'), (2, 'foo'), (4, 'hi'), (5, 'good'), (1, 'this'), (4, 'hi')]
      
    2. 您使用MultiDict,例如,您可以安装werkzeug

      $ pip install werkzeug
      

      然后你就可以使用multidict了:

      from werkzeug.datastructures import MultiDict
      d = MultiDict(zip(scores,text_results))

      然后您可以使用.getlist(key) 获取与键关联的值列表,例如:

      >>> d.getlist(4)
      ['hello', 'hi', 'hi']
      >>> d.getlist(2)
      ['foo']
      
    3. 您可以使用defaultdict 并自己构建映射到列表的字典:

      from collections import defaultdict
      
      d = defaultdict(list)
      for k,v in zip(scores,text_results):
          d[k].append(v)
      

    【讨论】:

    • 这很酷,没听说过 MultiDict。与defaultdict(list)相比有什么优势?
    • @ZevAverbach:我认为它提供了一个很好的界面,使您仍然可以使用映射到值的键。例如,查找 d[key] 将给出与键关联的第一个值。
    【解决方案4】:

    那么你应该使用列表,而不是字典。

    text_results = ['hello', 'foo' , 'hi' , 'good' , 'this' , 'hi' ]
    scores = [4,2,4,5,1,4]
    res_list = list(zip(scores,text_results)) 
    print res_list
    

    【讨论】:

    • 但是如果我想按照分数升序排列呢?
    • @AliJafar sorted(res_list)。降序:sorted(res_list, reverse=True).
    • 感谢@ZevAverbach
    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多