Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用变量名键向python字典添加项_Python_List_Dictionary - Fatal编程技术网

使用变量名键向python字典添加项

使用变量名键向python字典添加项,python,list,dictionary,Python,List,Dictionary,我从项目列表中列出了n个长度的可能组合列表,现在我想创建一个字典,其中每个键都是可能组合列表中的一个项目,因此我可以开始计算在一组观察中每个组合出现的次数(关联规则引擎编程的早期阶段). 以下是我所拥有的: 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 prin

我从项目列表中列出了n个长度的可能组合列表,现在我想创建一个字典,其中每个键都是可能组合列表中的一个项目,因此我可以开始计算在一组观察中每个组合出现的次数(关联规则引擎编程的早期阶段). 以下是我所拥有的:

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
导入itertools
stuff=(1,2,3,4)
n=1
combs=list()

当n时,可以使用元组作为键:

mydict = { (1, 2, 4): 0 }
如果您想计数,请看一看,它使计数变得微不足道,无需将键初始化为0:

counts = collections.Counter()
counts[(1, 2, 4)] += 1

(1,2,3)
存储为值而非键有什么不对。这是另一个问题,您可以通过尝试来回答这个问题-元组可以作为字典键。问题是不使用元组作为键,问题是如何循环遍历元组列表,并让python在字典中为每个元组生成一个键。但是如何让python遍历元组列表并将每个元组作为键添加到字典中?这就是问题所在,对不起,如果我措辞不当。就我所知,showcount[%s],%(item)]=0是个问题。@TomR:不,只要
showcount[item]+=1就足够了。不需要
showcount[item]=0
,因为
Counter
自动神奇地将每个新键设置为0。您只需使用
作为键,无需将其转换为字符串。