|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想用itertools的combinations函数求解三色球问题:
‘有红、黄、蓝三种颜色的球,其中红球 3 个,黄球 3 个,绿球 6 个。先将这 12 个球混合放在一个盒子中,从中任意摸出 8 个球,编程计算摸出球的各种颜色搭配。’
我的代码:
import itertools
ball_list = ['red','red','red','yellow','yellow','yellow','green','green','green','green','green','green']
result = list(itertools.combinations(ball_list,8))
result1 = []
for each in result:
if each not in result1:
result1.append(each)
for i in result1:
print(i)
输出结果:
('red', 'red', 'red', 'yellow', 'yellow', 'yellow', 'green', 'green')
('red', 'red', 'red', 'yellow', 'yellow', 'green', 'green', 'green')
('red', 'red', 'red', 'yellow', 'green', 'green', 'green', 'green')
('red', 'red', 'red', 'green', 'green', 'green', 'green', 'green')
('red', 'red', 'yellow', 'yellow', 'yellow', 'green', 'green', 'green')
('red', 'red', 'yellow', 'yellow', 'green', 'green', 'green', 'green')
('red', 'red', 'yellow', 'green', 'green', 'green', 'green', 'green')
('red', 'red', 'green', 'green', 'green', 'green', 'green', 'green')
('red', 'yellow', 'yellow', 'yellow', 'green', 'green', 'green', 'green')
('red', 'yellow', 'yellow', 'green', 'green', 'green', 'green', 'green')
('red', 'yellow', 'green', 'green', 'green', 'green', 'green', 'green')
('yellow', 'yellow', 'yellow', 'green', 'green', 'green', 'green', 'green')
('yellow', 'yellow', 'green', 'green', 'green', 'green', 'green', 'green')
问题:如何计算输出的个元组中red,yellow,green的个数
第一种方案:red = ?yellow = ?green = ?
。。。
第i种方案:red = ?yellow = ?green = ?
for i in result1:
print(i.count('red'), i.count('yellow'), i.count('green'))
|
|