【问题标题】:How to iterate through dict in random order in Python?如何在Python中以随机顺序遍历dict?
【发布时间】:2011-10-16 16:30:34
【问题描述】:

如何以随机顺序遍历字典的所有项目?我的意思是 random.shuffle,但对于字典。

【问题讨论】:

    标签: python random


    【解决方案1】:

    dict 是一组无序的键值对。当您迭代 dict 时,它实际上是随机的。但要显式随机化键值对序列,您需要使用不同的有序对象,例如列表。 dict.items()dict.keys()dict.values() 分别返回列表,可以打乱。

    items=d.items() # List of tuples
    random.shuffle(items)
    for key, value in items:
        print key, value
    
    keys=d.keys() # List of keys
    random.shuffle(keys)
    for key in keys:
        print key, d[key]
    

    或者,如果您不关心密钥:

    values=d.values() # List of values
    random.shuffle(values) # Shuffles in-place
    for value in values:
        print value
    

    你也可以“随机排序”:

    for key, value in sorted(d.items(), key=lambda x: random.random()):
        print key, value
    

    【讨论】:

    • 在 Python3 中,d.items()d.keys()d.values() 生成一个迭代器对象。您需要使用 list() 函数将该迭代器显式转换为列表。
    • “当您迭代 dict 时,它实际上是随机的” - 不是。考虑到像 int 这样的东西很可能按排序顺序出现,依赖它甚至看起来是随机的也是一个坏主意。另外,随机键排序是 O(nlog(n)) 而不是 O(n),所以应该避免。
    • 你会如何调整它以始终随机播放字典(以相同的方式维护右键与正确值之间的链接,例如使用 np.random.RandomState(100)
    【解决方案2】:

    正如Charles Brunet 已经说过的字典是键值对的随机排列。但是要使它真正随机,您将使用随机模块。 我写了一个函数,它会随机播放所有的键,所以当你迭代它时,你会随机迭代。看代码可以更清楚的理解:

    def shuffle(q):
        """
        This function is for shuffling 
        the dictionary elements.
        """
        selected_keys = []
        i = 0
        while i < len(q):
            current_selection = random.choice(q.keys())
            if current_selection not in selected_keys:
                selected_keys.append(current_selection)
                i = i+1
        return selected_keys
    

    现在,当您调用该函数时,只需传递参数(您要洗牌的字典的名称),您将获得一个已洗牌的键列表。最后,您可以为列表的长度创建一个循环,并使用name_of_dictionary[key] 来获取值。

    【讨论】:

    • 您最好使用现成的洗牌或置换函数,例如numpy.random.permutation()。但如果你真的想自己做,这似乎是一种非常缓慢的洗牌方式!假设您有一个带有 10k 个键的 dict,并且您只剩下最后一个键。想象一下,在您选择它之前,您必须经历多少次失败的尝试!为了改进您的算法,您可以在每次迭代中从候选中删除每个选定的键,以便您仅从剩余的键中进行选择。
    【解决方案3】:

    你不能。使用.keys() 获取键列表,将它们打乱,然后在索引原始字典的同时遍历列表。

    或者使用.items(),然后随机播放和迭代。

    【讨论】:

    • 或者dict.values(),如果你想要的只是这些值。
    • 不能或不会? for item in random.sample(list(d.values()), len(d)):
    【解决方案4】:
    import random
    
    def main():
    
        CORRECT = 0
    
        capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau',
            'Arizona': 'Phoenix', 'Arkansas': 'Little Rock'} #etc... you get the idea of a dictionary
    
        allstates = list(capitals.keys()) #creates a variable name and list of the dictionary items
        random.shuffle(allstates) #shuffles the variable
    
        for a in allstates: #searches the variable name for parameter
            studentinput = input('What is the capital of '+a+'? ')
            if studentinput.upper() == capitals[a].upper():
                CORRECT += 1
    main()
    

    【讨论】:

      【解决方案5】:

      我想要一种快速遍历随机列表的方法,因此我编写了一个生成器:

      def shuffled(lis):
          for index in random.sample(range(len(lis)), len(lis)):
              yield lis[index]
      

      现在我可以像这样遍历我的字典 d

      for item in shuffled(list(d.values())):
          print(item)
      

      或者如果您想跳过创建新函数,这里有一个 2-liner:

      for item in random.sample(list(d.values()), len(d)):
          print(item)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-09
        • 2013-06-02
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 1970-01-01
        • 2015-01-22
        相关资源
        最近更新 更多