python统计打印

2024-06-16 14:14:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,[(falseName, realName, positionOfMistake)]例如:

[('Milter', 'Miller', 4),
 ('Manton','Manson',4), 
 ('Moller', 'Miller', 2)] 

我需要写一个函数返回:

^{pr2}$

我在想:

def nameStatistics(nameList):
    D={}
    for tup in nameList
        if tup[1] not in D:
            D[tup[1]]={}
            if tup[0] not in D[tup[1]]:
                D[tup[1]][tup[0]]=0
            D[tup[1]][tup[0]] += 1
            print tup[1]+":\n\t"+tup[0]

但从中我得到:

  Miller:
        Milter 
  Miller:     
        Moller
  Manson:
        Manton

Tags: in列表ifnotmilter元组tupmiller
1条回答
网友
1楼 · 发布于 2024-06-16 14:14:11

你没有正确地建立你的字典,因为你的缩进在几个地方是错误的。另外,print语句不引用您构建的字典。试试这个:

def nameStatistics(nameList):
    D={}
    for firstName, lastName, unused in nameList:
        if lastName not in D:
            D[lastName]={}
        if firstName not in D[lastName]:
            D[lastName][firstName] = 0
        D[lastName][firstName] += 1
    # only print after all tuples are processed
    for lastName, stats in D.iteritems():
        print lastName + "\n"
        for firstName, frequency in stats.iteritems():
            print "\t{0}:  {1}\n".format(firstName, frequency/float(len(stats)))

您可以使用^{}进一步简化此过程:

^{pr2}$

相关问题 更多 >