Shuffle two list at once with same order

前端 未结 6 720
感动是毒
感动是毒 2021-01-30 03:38

I\'m using the nltk library\'s movie_reviews corpus which contains a large number of documents. My task is get predictive performance of these reviews

6条回答
  •  面向向阳花
    2021-01-30 04:17

    Shuffle an arbitray number of lists simultaneously.

    from random import shuffle
    
    def shuffle_list(*ls):
      l =list(zip(*ls))
    
      shuffle(l)
      return zip(*l)
    
    a = [0,1,2,3,4]
    b = [5,6,7,8,9]
    
    a1,b1 = shuffle_list(a,b)
    print(a1,b1)
    
    a = [0,1,2,3,4]
    b = [5,6,7,8,9]
    c = [10,11,12,13,14]
    a1,b1,c1 = shuffle_list(a,b,c)
    print(a1,b1,c1)
    

    Output:

    $ (0, 2, 4, 3, 1) (5, 7, 9, 8, 6)
    $ (4, 3, 0, 2, 1) (9, 8, 5, 7, 6) (14, 13, 10, 12, 11)
    

    Note:
    objects returned by shuffle_list() are tuples.

    P.S. shuffle_list() can also be applied to numpy.array()

    a = np.array([1,2,3])
    b = np.array([4,5,6])
    
    a1,b1 = shuffle_list(a,b)
    print(a1,b1)
    

    Output:

    $ (3, 1, 2) (6, 4, 5)
    

提交回复
热议问题