Better way to shuffle two related lists

后端 未结 7 2205
星月不相逢
星月不相逢 2020-12-13 09:24

Is there better ways to randomly shuffle two related lists without breaking their correspondence in the other list? I\'ve found related questions in numpy.array

相关标签:
7条回答
  • 2020-12-13 10:28

    If you have to do this often, you could consider adding one level of indirection by shuffling a list of indexes.

    Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on
    win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import random
    >>> a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
    >>> b = [2, 4, 6, 8, 10]
    >>> indexes = range(len(a))
    >>> indexes
    [0, 1, 2, 3, 4]
    >>> random.shuffle(indexes)
    >>> indexes
    [4, 1, 2, 0, 3]
    >>> for index in indexes:
    ...     print a[index], b[index]
    ...
    [9, 10] 10
    [3, 4] 4
    [5, 6] 6
    [1, 2] 2
    [7, 8] 8
    
    0 讨论(0)
提交回复
热议问题