【问题标题】:printing dict keys 'value' times and alternatively like round robin scheduling打印 dict 键“值”时间,或者像循环调度
【发布时间】:2014-02-13 23:11:26
【问题描述】:
obj = {'a1':3,'a2':5,'a3':1}

我知道如何迭代它:

for k,v in obj.iteritems():
    print k

输出:

a1 a2 a3

为了打印密钥value 次,我做到了:

for k,v in obj.iteritems():
    for v in range(0,v):
        print k

我得到的输出:

a1 a1 a1 a2 a2 a2 a2 a2 a3

但我希望输出基于value 次然后交替:

期望的输出:

a1 a2 a3 a1 a2 a1 a2 a2 a2

【问题讨论】:

  • 您想要按排序顺序排列的键吗?您在当前代码中得到它们的事实是巧合。

标签: loops python-2.7 dictionary


【解决方案1】:

使用 itertools 的配方。您需要使用来自 itertools 页面 hereroundrobin 配方,下面也有重复:

from itertools import islice, cycle, repeat

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))


# Now, the real recipe starts
obj = {'a1':3,'a2':5,'a3':1}
objiter = [repeat(x,y) for x,y in obj.items()]
objlist = list(roundrobin(*objiter))
objlist
['a1', 'a3', 'a2', 'a1', 'a2', 'a1', 'a2', 'a2', 'a2']

请注意,这并没有准确地为您提供所需的内容...正如其他答案之一所说,您可以使用字典的排序版本(也包括在下面),或者您可以使用 OrderedDict首先。请记住,如果您使用 OrderedDict 并将其初始化为 my_odict = OrderedDict({1:1, 2:2, 3:3}),python 将首先创建字典 - 无序 - 然后从中创建 OrderedDict,这可能不是您想要的。

排序:

objiter = [repeat(x, obj[x]) for x in sorted(obj.keys())]
objlist = list(roundrobin(*objiter))
objlist
['a1', 'a2', 'a3', 'a1', 'a2', 'a1', 'a2', 'a2', 'a2']

很明显,有序字典recipe和普通字典recipe是一样的,只是传入一个有序字典。

【讨论】:

  • 完美回答! +1
【解决方案2】:

实际上并没有一种巧妙的方法来做到这一点。您可以采用这种方法,复制obj,然后使用副本中的值来跟踪每个键到print 的次数:

out = obj.copy()
while sum(out.values()):
    for k in sorted(out):
        if out[k]:
            print k
            out[k] -= 1

【讨论】:

  • 是的,如果您有大量数据,将sorted 移出循环会更有效。
【解决方案3】:

单线:(假设None not in obj

[x for y in map(None, *[[k]*v for k, v in sorted(obj.iteritems())]) for x in y if x is not None]

【讨论】:

    【解决方案4】:

    单线不使用额外空间(sorted 可能使用额外的 O(n) 空间),python 3:

    from itertools import chain, zip_longest, repeat
    obj = {'a1':3,'a2':5,'a3':1}
    [x for x in chain(*zip_longest(*(repeat(k, v) for k,v in sorted(obj.items())))) if x is not None]
    

    【讨论】:

      【解决方案5】:
      for i in xrange(0, max(obj.values())):
          for k,v in obj.iteritems():
              if v > i:
                 print k
      

      【讨论】:

      • 返回 - a3 a3 a1 a3。第一行也缺少右大括号
      猜你喜欢
      • 2017-09-09
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多