python创建变量名软件_使用变量名键将项目添加到字典python

I made a list of lists of possible combinations of n length from a list of items, and now I want to create a dictionary where each key is one of the items from list of lists of possible combinations, so I can start counting how many times each combination occurs in a set of observations (early stages of programming an association rules engine). Here's what I have:

import itertools

stuff=(1,2,3,4)

n=1

combs=list()

while n<=len(stuff):

combs.append(list(itertools.combinations(stuff,n)))

n = n+1

print combs

viewers={'Jim':(1,3,4), 'Bob':(1,2,4), 'Jerry':(1,4), 'Ben':(2), 'Sal':(1,4)}

showcount={}

for list in combs:

for item in list:

showcount["%s",%(item)]=0

print viewers

print showcount

How do I get the item to appear as the key in the dictionary? So for example, I'd like the combination '(1,2,4):0' to be a key value pair so I can later count the number of times '(1,2,4)' appears. I'm pretty new to Python, but I did seach around for an answer and couldn't find one. Apologies if this has been answered and I just couldn't find it.

解决方案

You can use tuples as keys:

mydict = { (1, 2, 4): 0 }

If you want to count things, take a look at collections.Counter, it makes counting trivial, no need to initialize the keys to 0:

counts = collections.Counter()

counts[(1, 2, 4)] += 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值