首页 > 解决方案 > 如何使用python计算字典中的元素?

问题描述

这是我的字典:

{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Attribute']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}
{'com.sunlightlabs.android.congress.fragments.LegislatorProfileFragment': ['Move Method']}

键是类的名称,值是重构类型,在这个例子中我只有一个类,它包含 1 个移动属性和 7 个移动方法。

我用这段代码来计算每个类中重构类型的数量

import csv
import pandas as pd
df=pd.read_csv('output2.csv', sep=',')
df1 = df[['RefactoringType','RefactoringDetail']]
df1['Detail']=df.RefactoringDetail.str.extract(r'[C|c]lass\s*([^ ]*)')
del df1['RefactoringDetail']

#this part generate the map 
my_map={}
for i in range(df1.shape[0]):
  my_map[df1['Detail'][i]] = []
  my_map[df1['Detail'][i]].append(df1['RefactoringType'][i])
  print(my_map)

#define all refactoring operations  
all_refactorings=['Extract Superclass','Move Attribute','Extract Method','Inline Method','Rename Method','Move Method','Rename Package','Move Attribute','Pull Up Method','Pull Up Attribute','Push Down Method','Push Down Attribute','Move Class','Rename Class','Move And Rename Class','Extract And Move Method','Move Source Folder','Change Package','Extract Variable','Rename Attribute','Move and Rename Attribute','Replace Variable with Attribute','Replace Attribute ','Merge Variable','Merge Parameter','Merge Attribute','split Variable','split Parameter','Split Attribute','Extract Interface']
newdf = pd.DataFrame(columns= ['Class'] + all_refactorings )

for class_name in my_map :
  new_row = {ref:0 for ref in all_refactorings} 
  new_row['Class'] = class_name
  for ref_type in my_map[class_name] :
    new_row[ref_type] += 1 
  newdf=newdf.append(new_row, ignore_index=True)
newdf

它为我返回:

Class   Extract Superclass  Move Attribute  Extract Method  Inline Method   Rename Method   Move Method Rename Package  Move Attribute  Pull Up Method  Pull Up Attribute   Push Down Method    Push Down Attribute Move Class  Rename Class    Move And Rename Class   Extract And Move Method Move Source Folder  Change Package  Extract Variable    Rename Attribute    Move and Rename Attribute   Replace Variable with Attribute Replace Attribute   Merge Variable  Merge Parameter Merge Attribute split Variable  split Parameter Split Attribute Extract Interface
com.sunlightlabs.android.congress.fragments.Le...   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

我找不到错误在哪里它应该给我 7 移动方法和 1 移动属性!

请提供任何帮助

标签: pythondictionarycount

解决方案


推荐阅读