改善两个相关列表的更好方法

clw*_*wen 31 python shuffle list

有没有更好的方法随机洗牌两个相关的列表而不打破其他列表中的对应?我发现相关问题在numpy.arrayc#,但不完全一样的.

作为第一次尝试,一个简单的zip技巧将做:

import random
a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
b = [2, 4, 6, 8, 10]
c = zip(a, b)
random.shuffle(c)
a = [e[0] for e in c]
b = [e[1] for e in c]
print a
print b
Run Code Online (Sandbox Code Playgroud)

它将获得输出:

[[1, 2], [7, 8], [3, 4], [5, 6], [9, 10]]
[2, 8, 4, 6, 10]
Run Code Online (Sandbox Code Playgroud)

只是发现它有点尴尬.它还需要一个额外的清单.

koj*_*iro 44

鉴于问题中展示的关系,我将假设列表的长度相同,并且list1[i]对应list2[i]于任何索引i.有了这个假设,改组列表就像改组索引一样简单:

对于Python2.x:

 from random import shuffle
 # Given list1 and list2

 list1_shuf = []
 list2_shuf = []
 index_shuf = list(range(len(list1)))
 shuffle(index_shuf)
 for i in index_shuf:
     list1_shuf.append(list1[i])
     list2_shuf.append(list2[i])
Run Code Online (Sandbox Code Playgroud)

对于Python 3.x:

 from random import shuffle
 # Given list1 and list2

 list1_shuf = []
 list2_shuf = []
 index_shuf = list(range(len(list1)))
 shuffle(index_shuf)
 for i in index_shuf:
     list1_shuf.append(list1[i])
     list2_shuf.append(list2[i])
Run Code Online (Sandbox Code Playgroud)

  • 作为列表推导的粉丝:list1_shuf = [list1 [i] for i in index_shuf] (15认同)

小智 22

如果您愿意再安装一些软件包:

要求:NumPy(> = 1.6.1),SciPy(> = 0.9).

pip install -U scikit-learn

from sklearn.utils import shuffle
list_1, list_2 = shuffle(list_1, list_2)
Run Code Online (Sandbox Code Playgroud)


Jer*_*own 6

如果必须经常这样做,可以考虑通过混洗索引列表来添加一个间接级别.

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
Run Code Online (Sandbox Code Playgroud)