Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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 2.7 从键字典中的元组列表中计算部分_Python 2.7_List_Dictionary_Count_Tuples - Fatal编程技术网

Python 2.7 从键字典中的元组列表中计算部分

Python 2.7 从键字典中的元组列表中计算部分,python-2.7,list,dictionary,count,tuples,Python 2.7,List,Dictionary,Count,Tuples,我有一个大型字典,其中的键由元组值组成,如下所示: Ft = {('Car', 'Blue', 'C1'): 1, ('Bike', 'Red', 'C3'): 10, ('Car', 'Blue', 'C8'): 7, ('Bike', 'Red', 'C12'): 12. ('Car', 'Blue', 'C13'): 5, ('Bus', 'Blue', 'C14'): 17} Count_appearance = {} for k in list(set(bcc)): Coun

我有一个大型字典,其中的键由元组值组成,如下所示:

Ft = {('Car', 'Blue', 'C1'): 1, ('Bike', 'Red', 'C3'): 10, ('Car', 'Blue', 'C8'): 7, ('Bike', 'Red', 'C12'): 12. ('Car', 'Blue', 'C13'): 5, ('Bus', 'Blue', 'C14'): 17}
Count_appearance = {}
for k in list(set(bcc)):
    Count_quays[k] = bcc.count(k)

>>> print Count_appearance
{('Car', 'Blue'): 3, ('Bike', 'Red'): 2, ('Bus', 'Blue'): 1}
我的目标是计算元组键的前两个值的数量,并将其设置到字典中进行进一步计算。目前我是这样做的:

bcc = [] 
for key, value in Ft.iteritems():
    bcc.append((key[0],key[1]))

>>>print bcc 
[('Car', 'Blue'), ('Bike', 'Red'), ('Car', 'Blue'), ('Bike', 'Red'), ('Car', 'Blue'), ('Bus', 'Blue')]
然后我将使用.count计算de值,如下所示:

Ft = {('Car', 'Blue', 'C1'): 1, ('Bike', 'Red', 'C3'): 10, ('Car', 'Blue', 'C8'): 7, ('Bike', 'Red', 'C12'): 12. ('Car', 'Blue', 'C13'): 5, ('Bus', 'Blue', 'C14'): 17}
Count_appearance = {}
for k in list(set(bcc)):
    Count_quays[k] = bcc.count(k)

>>> print Count_appearance
{('Car', 'Blue'): 3, ('Bike', 'Red'): 2, ('Bus', 'Blue'): 1}
因为我必须在更大的数据集上使用它几次,所以我觉得它有点像“spagetti编码”,首先制作一个列表,然后对列表进行计数

有没有一种更简单/更快的方法可以让字典从Ft中计数

使用子类的简短解决方案:

import collections

Ft = {('Car', 'Blue', 'C1'): 1, ('Bike', 'Red', 'C3'): 10, ('Car', 'Blue', 'C8'): 7, ('Bike', 'Red', 'C12'): 12, ('Car', 'Blue', 'C13'): 5, ('Bus', 'Blue', 'C14'): 17}
counts = dict(collections.Counter(k[:2] for k in Ft))

print counts
输出:

{('Bike', 'Red'): 2, ('Car', 'Blue'): 3, ('Bus', 'Blue'): 1}

顺便说一句,我使用[python-2.7]计数器键[0],键[1]作为Ft中的键?你能在没有计数器的情况下得到输出吗?