我有乐透的优惠券:
coupons = [[1,4,7,34,45,67], [2,8,16,34,35,38] ... ]
和结果:
result = [7,12,13,26,29,34]
我怎样才能在优惠券()上数数我的得奖数字--?我想要返回统计数据,例如:
statistics = [20, 15, 11, 1, 0, 0, 0]
哪里
统计数字-0获胜号码的优惠券数量,
statistics1 -有1个中奖号码的优惠券,
statistics2 -两个中奖号码的优惠券数量,
statistics3 -3个中奖号码的优惠券数量,
statistics4 -有4个中奖号码的优惠券,
statistics5 -有5个中奖号码的优惠券,
statistics6 -6个中奖号码的优惠券数量
发布于 2012-11-06 22:22:49
试试这个:
from collections import Counter
coupons = [[1,4,7,34,45,67] , [2,8,16,34,35,38],
[7,12,13,26,29,34], [1,2,3,4,5,6]]
result = [7,12,13,26,29,34]
answer = Counter([6-len(set(result)-set(s)) for s in coupons])
最后一行是请求的一条线。请注意,我必须更改内部使用的数据结构才能工作-优惠券和结果现在都是用集合表示的,结果存储在Counter
(一种特殊类型的字典)中,但对于所有实际目的,答案都是一个数组:
answer[0]
> 1
...
answer[6]
> 1
更新
好的,我设法在一行中压缩到实际列表的转换。它没有效率(您最好使用上面我的第一个解决方案),但是,它是有效的,并且是单行的:
[Counter([6-len(set(result)-set(s)) for s in coupons])[x] for x in xrange(7)]
发布于 2012-11-06 22:21:04
如果不将导入计算为“一行”,则这将在一行中生成结果:
>>> coupons = [[1,4,7,34,45,67], [2,8,16,34,35,38], [1,4,7,13,55],
[7,12,13,26,29,19]]
>>> result = [7,12,13,26,29,34]
>>>
>>> import collections
>>> collections.Counter(len(set(c).intersection(set(result))) for c in coupons)
Counter({2: 2, 1: 1, 5: 1})
发布于 2012-11-06 22:20:56
以下是这项工作:
from collections import *
cnt = defaultdict(int, Counter(len(set(result) & set(c)) for c in coupons))
statistics = [cnt[n] for n in range(7)]
这可以通过用分号将这三个语句分隔成一行代码,虽然我看不出这样做除了使代码更难阅读之外,还能达到什么效果。
如果statistics
不必是一个列表,那么可以删除对defaultdict()
的调用以及最后一行,直接使用Counter
实例。
https://stackoverflow.com/questions/13260234
复制相似问题