从python中的列表返回两个随机选择的组

时间:2016-05-01 21:18:32

标签: python list random

我如何编写代码,将9个人的列表尽可能均匀地分成2辆车,但是他们会在python中随机放入每辆车? 基本上我正在寻找类似于此的回报:
    车1:人8,人2,人4,人7     车2:Person5,Person1,Person3,Person6,Person9

2 个答案:

答案 0 :(得分:1)

只需将整个列表洗牌,然后将该列表分成两个夹头,一个包含4个人,另一个包含其余的:

import random

people = ['foo', 'bar', 'baz', 'eggs', 'ham', 'spam', 'eric', 'john', 'terry']
random.shuffle(people)
car1, car2 = people[:4], people[4:]

如果您无法直接对人员列表进行排序,请改为使用random.sample()

people = ['foo', 'bar', 'baz', 'eggs', 'ham', 'spam', 'eric', 'john', 'terry']
shuffled = random.sample(people, len(people))
car1, car2 = shuffled[:4], shuffled[4:]

后一种方法的演示:

>>> import random
>>> people = ['foo', 'bar', 'baz', 'eggs', 'ham', 'spam', 'eric', 'john', 'terry']
>>> shuffled = random.sample(people, len(people))
>>> shuffled[:4], shuffled[4:]
(['bar', 'baz', 'terry', 'ham'], ['spam', 'eric', 'foo', 'john', 'eggs'])

答案 1 :(得分:1)

from random import shuffle
x = [i for i in range(10)]
shuffle(x)
print x
mid = int(len(x)/2)
car1 = x[:mid]
car2 = x[mid:]
print car1
print car2