改组两个相关列表的更好方法 [英] Better way to shuffle two related lists

查看:48
本文介绍了改组两个相关列表的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法可以随机地随机排列两个相关列表,而又不会破坏它们在另一个列表中的对应关系?我在numpy.arrayc#中发现了相关问题,但不完全相同.

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 and c# but not exactly the same one.

首先尝试做一个简单的zip技巧:

As a first try, a simple zip trick will do:

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

它将获得输出:

[[1, 2], [7, 8], [3, 4], [5, 6], [9, 10]]
[2, 8, 4, 6, 10]

只是觉得有点尴尬.并且还需要一个附加列表.

Just find it a bit awkward. And it also need an additional list as well.

推荐答案

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

Given the relationship demonstrated in the question, I'm going to assume the lists are the same length and that list1[i] corresponds to list2[i] for any index i. With that assumption in place, shuffling the lists is as simple as shuffling the indices:

 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])

这篇关于改组两个相关列表的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆