如果多次声明,则打印C文件变量

时间:2016-01-18 11:28:22

标签: python

for cVariable in CFile.Variables:
    occCtr=0
    for cVar2 in CFile.Variables:
        if  cVariable.Name == cVar2.Name:
            occCtr+=1
    if occCtr > 1:
        res = False
        errmsg += cVariable.Name + ' is declared more than once ' + '\n'

这是我的算法。它正在解析C文件并查明变量是否被多次声明。但是,当我打印错误消息时,它向我显示了两个具有相同名称的变量,我只需要从每个变量中打印一个

1 个答案:

答案 0 :(得分:0)

from collections import Counter

declarations = Counter(var.Name for var in CFile.Variables)
duplicates = [
    "{} is declared {} times".format(name, times)
    for name, times in declarations.items() where times > 1
]
duplicates.sort()
error_msg = "\n".join(duplicates)