我会如何编写代码,其中包含9人的列表,尽可能均匀地分成2个汽车,但是他们是随机放入每辆汽车的蟒蛇中的? 基本上我在找一个类似的回报:
车1:Person8,PERSON2,Person4,Person7
汽车2:Person5,PERSON1,Person3可能,Person6,Person9从python列表中返回两个随机选择的组
-1
A
回答
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
相关问题
- 1. Python不从列表中随机选择
- 2. 随机选择一个公式,并从列表中回答 - PYTHON
- 3. 从数组列表中随机选择
- 4. Python列表随机选择
- 5. 从列表元组返回随机值
- 6. 随机选择从列表
- 7. Python:从多个列表中随机选择,无重复
- 8. 如何从列表中随机选择一个元组?
- 9. 从数组列表中随机选择一个段落Javascript
- 10. 从下拉列表中随机选择?
- 11. 从Java列表中随机选择[]
- 12. 从列表中选择随机段落
- 13. 从列表中选择随机短语
- 14. 从下拉列表中随机选择?
- 15. 如何从Python中的列表中随机选择?
- 16. 从Python中的前一个选择中随机选择
- 17. Adodb:Postgresql从两个表中选择,但返回一组结果
- 18. 随机选择两个值
- 19. 选择从列表中的两个元组和在Python
- 20. 返回两个列表python?
- 21. Python |避免从列表中随机选择以前的值
- 22. 从随机到不随机选择列
- 23. 随机选择Python列表中的列表,取决于权重
- 24. 随机数存储在数组列表中,并从中选择
- 25. 从Python列表中选择随机项目
- 26. Python - 从列表中选择随机对象
- 27. 从条件列表中随机选择 - Python
- 28. 随机从列表中使用random.randint选择python
- 29. 从列表中选择非随机对象Python
- 30. 的MySQL选择一个随机行从两个连接表
通常人们希望看到你试过的东西。 – dbliss