【问题标题】:Iterate through Python dictionary and special append to new list?遍历 Python 字典并特殊追加到新列表?
【发布时间】:2019-07-15 01:51:05
【问题描述】:

我想遍历一个字典,并将每个键(字母)按其值(频率)的次数重复附加到一个新列表中。

例如: 输入:{'A':1, 'B':2}。预期输出:['A', 'B', 'B']

我正在做的事情不起作用。我在我的函数中写什么来做到这一点?

def get_freq_dict():
    freq_dict = {'J' : 1, 'K' : 1, 'Q' : 1, 'X' : 1, 'Z' : 1,\
                'B' : 2, 'C' : 2, 'F' : 2, 'H' : 2, 'M' : 2, 'P' : 2,\
                'V' : 2, 'W' : 2, 'Y' : 2, '' : 2,\
                'G' : 3, 'D' : 4, 'L' : 4, 'S' : 4, 'U' : 4,\
                'N' : 6, 'R' : 6, 'T' : 6, 'O' : 8, 'A' : 9, 'I' : 9,\
                'E' : 12}
    return freq_dict


def bag_of_letters(freq_dict):
    freq_lst = [] 
    for key, value in freq_dict.items():
        for range in(value):
            freq_lst.append(value)
    return freq_lst


def main():

    freq_dict = get_freq_dict()
    freq_lst = bag_of_letters(freq_dict)

    print(freq_dict, freq_lst)
main()

【问题讨论】:

标签: python loops dictionary append key-value


【解决方案1】:

您应该改为遍历 range,并附加 key 而不是 value

for key, value in freq_dict.items():
    for _ in range(value):
        freq_lst.append(key)

或者,您可以使用列表推导:

def bag_of_letters(freq_dict):
    return [i for k, v in freq_dict.items() for i in [k] * v]

【讨论】:

  • freq_lst.extend([key]*value) ?
  • 谢谢你,这更有意义。但是我仍然遇到打印输出的问题。它给了我我正在寻找的东西,但也给了我最上面的原始字典。 ex - {'J': 1, 'K': 1, 'Q': 1,'.... ['J', 'K', 'Q', .....]} 我在哪里因为是 ['J', 'K', 'Q', .....]}
  • @Tim 你可以用print(freq_lst) 代替print(freq_dict, freq_lst)
【解决方案2】:

罪魁祸首

for range in(value):
    freq_lst.append(value)

救援者

for i in range(value):
     freq_lst.append(key)

因此

def get_freq_dict():
    freq_dict = {'J' : 1, 'K' : 1, 'Q' : 1, 'X' : 1, 'Z' : 1,\
                'B' : 2, 'C' : 2, 'F' : 2, 'H' : 2, 'M' : 2, 'P' : 2,\
                'V' : 2, 'W' : 2, 'Y' : 2, '' : 2,\
                'G' : 3, 'D' : 4, 'L' : 4, 'S' : 4, 'U' : 4,\
                'N' : 6, 'R' : 6, 'T' : 6, 'O' : 8, 'A' : 9, 'I' : 9,\
                'E' : 12}
    return freq_dict


def bag_of_letters(freq_dict):
    freq_lst = []
    for key, value in freq_dict.items():
       # print(key, value)
        for i in range(value):
            freq_lst.append(key)
    return freq_lst


def main():

    freq_dict = get_freq_dict()
    freq_lst = bag_of_letters(freq_dict)

    print(freq_lst)
main()

输出

['J', 'K', 'Q', 'X', 'Z', 'B', 'B', 'C', 'C', 'F', 'F', 'H', 'H', 'M', 'M', 'P', 'P', 'V', 'V', 'W', 'W', 'Y', 'Y', '', '', 'G', 'G', 'G', 'D', 'D', 'D', 'D', 'L', 'L', 'L', 'L', 'S', 'S', 'S', 'S', 'U', 'U', 'U', 'U', 'N', 'N', 'N', 'N', 'N', 'N', 'R', 'R', 'R', 'R', 'R', 'R', 'T', 'T', 'T', 'T', 'T', 'T', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E']

如果您希望它们完美配对

 for i in range(value):
     freq_lst.append([key]*value)

OP但是我在打印输出时仍然遇到问题。它给了我我正在寻找的东西,但也给了我最上面的原始字典

Ans:因为您同时打印dictlist

print(freq_dict, freq_lst)

只需打印list

print(freq_lst)

编辑 2:

使用groupby() 将相似元素组合在一起的另一种更好的方法:

仅附加 key

 for i in range(0, value):
      freq_lst.append(key)

然后:

 print([list(j) for i, j in groupby(freq_lst)])

输出

[['J'], ['K'], ['Q'], ['X'], ['Z'], ['B', 'B'], ['C', 'C'], ['F', 'F'], ['H', 'H'], ['M', 'M'], 
 ['P', 'P'], ['V', 'V'], ['W', 'W'], ['Y', 'Y'], ['', ''], ['G', 'G', 'G'], 
 ['D', 'D', 'D', 'D'], ['L', 'L', 'L', 'L'], ['S', 'S', 'S', 'S'], ['U', 'U', 'U', 'U'], 
 ['N', 'N', 'N', 'N', 'N', 'N'], ['R', 'R', 'R', 'R', 'R', 'R'], 
 ['T', 'T', 'T', 'T', 'T', 'T'], ['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'], 
 ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'], 
 ['I', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I'], 
 ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E']]

【讨论】:

    【解决方案3】:

    你来了

    freq_dict = {'J' : 1, 'K' : 1, 'Q' : 1, 'X' : 1, 'Z' : 1,\
                'B' : 2, 'C' : 2, 'F' : 2, 'H' : 2, 'M' : 2, 'P' : 2,\
                'V' : 2, 'W' : 2, 'Y' : 2, '' : 2,\
                'G' : 3, 'D' : 4, 'L' : 4, 'S' : 4, 'U' : 4,\
                'N' : 6, 'R' : 6, 'T' : 6, 'O' : 8, 'A' : 9, 'I' : 9,\
                'E' : 12}
    
    
    def bag_of_letters():
        freq_lst = []
    
        for key in freq_dict:
            for i in range(0, freq_dict[key]):
                freq_lst.append(key)
    
        return freq_lst
    
    
    def main():
        freq_lst = bag_of_letters()
        print(freq_lst)
    
    
    main()
    

    结果 ['J', 'K', 'Q', 'X', 'Z', 'B', 'B', 'C', 'C', 'F', 'F', ' H', 'H', 'M', 'M', 'P', 'P', 'V', 'V', 'W', 'W', ecc]

    【讨论】:

      【解决方案4】:

      你可以利用事实

      如果调用 items()、keys()、values()、iteritems()、iterkeys() 和 itervalues() 时没有对字典进行干预修改,则列表将直接对应。

      this topic 所示,因此您可以这样做:

      import itertools
      x = {'A':1, 'B':2}
      out = list(map(lambda x,y: [x]*y, x.keys(), x.values()))
      print(out) #[['A'], ['B', 'B']]
      out = list(itertools.chain.from_iterable(out))
      print(out) #['A', 'B', 'B']
      

      我使用itertools 来扁平化列表,如果你不希望import itertools 你可以这样做:

      out = sum(out,[])
      

      而不是

      out = list(itertools.chain.from_iterable(out))
      

      【讨论】:

        【解决方案5】:

        您可以通过Counter轻松做到这一点:

        from collections import Counter
        
        d = {'C': 3, 'B': 2, 'A': 1}
        c = Counter(d)
        list(c.elements())
        # ['C', 'C', 'C', 'B', 'B', 'A']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-01
          • 1970-01-01
          • 2016-06-22
          • 1970-01-01
          相关资源
          最近更新 更多