2016-05-01 73 views
-1

我会如何编写代码,其中包含9人的列表,尽可能均匀地分成2个汽车,但是他们是随机放入每辆汽车的蟒蛇中的? 基本上我在找一个类似的回报:
车1:Person8,PERSON2,Person4,Person7
汽车2:Person5,PERSON1,Person3可能,Person6,Person9从python列表中返回两个随机选择的组

+0

通常人们希望看到你试过的东西。 – dbliss

回答

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