【问题标题】:Randomize dictionary sorting随机字典排序
【发布时间】:2014-05-26 20:39:54
【问题描述】:

我一直在考虑这个问题,但我没有得出任何结论(Python 还不是很好)。

我的字典是这样的:

{1: [dog, animal], 2: [square, shape], 3: [red, color]}

我正在打印值,但字典是按数字排序的,这很好,但我想将它随机化,所以我打印出如下内容:

3
red
color
1
dog
animal
2
square
shape

我知道该列表更适合这种情况,但此数据来自我无法更改的现有结构。也许重新编号键可以解决问题?

【问题讨论】:

    标签: python python-2.7 random dictionary


    【解决方案1】:

    字典已经以任意顺序列出,它们没有固定的顺序。见Why is the order in dictionaries and sets arbitrary?任何顺序感都是巧合,取决于字典的插入和删除历史。

    也就是说,使用random.shuffle() 进一步确保随机列表很容易:

    import random
    
    items = yourdict.items()
    random.shuffle(items)
    
    for key, value in items:
        print key
        print '\n'.join(value)
    

    【讨论】:

    • 不错!您可以将 os.linesep 用作与平台无关的行分隔符:) +1 链接
    • @ReutSharabani:写入文本文件时,已经为您翻译了换行符。使用 print 时,您也不需要使用特定于平台的行分隔符。
    • 好吧...公平地说,任意random不同。
    【解决方案2】:

    您可以随机化密钥:

    import random
    ....
    keys = dictionary.keys()
    random.shuffle(keys)
    for key in keys:
        print key, dictionary[key]
    

    【讨论】:

    • 我会做keys = list(dictionary) 使其向前兼容。
    • 你能详细说明一下吗? python.org 在关于items() 的注释中使用了keys(),而keys() 本身什么也没说...
    • 在 python3.x 中,keys 返回一个与set 类似的对象。 IIRC,它不支持random.shuffle 要求的索引。 list(d) 提供的内容与 d.keys() 在 python2.x 中提供的内容相同。
    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    相关资源
    最近更新 更多