嵌套for循环,迭代,计算一个项目的多次出现

Nested for-loops, iteration, count multiple occurences of an item

这是一段代码,在底部,在代码的 ' ' 'commented out section' ' ' 中,有一行令我感到惊讶。请看:

#!/path/to/python 
#-*- coding: utf-8 -*-
def frequencer(sliced):    
    podium = []  
    for item in sliced:
        scat = len(sliced)
        print ("le the first scat for the word ' {0} ' is '{1} '.".format(item, scat))
        for indice in range (len(sliced)):
            print("indice = ", indice)
            print("sliced[indice]",sliced[indice])
            if sliced[indice] == item:
                print ("sliced[indice] is equal to ' {0} ', identical to ' {1} ' item.".format(sliced[indice], item))
                scat -= 1
                print("scat is equal to ' {0} '.".format(scat))
        print("scat exdented: ", scat)
        frequence = len(sliced) - scat
        print("frequence: ", frequence)
        podium += [frequence]
        print("podium: ", podium)
    print("podium: ", podium)
    return(max(podium))
print(frequencer( ['Here', 'is', 'a', 'line', 'like', 'sparkling', 'wine', 'Line', 'up', 'now', 'behind', 'the', 'cow']))

'''
le the first scat for the word ' line ' is '13 '.
indice =  0
sliced[indice] Here
indice =  1
sliced[indice] is
indice =  2
sliced[indice] a
indice =  3
sliced[indice] line
sliced[indice] is equal to ' line ', identical to ' line ' item.
scat is equal to ' 12 '.
indice =  4
sliced[indice] like
indice =  5
sliced[indice] sparkling
indice =  6
sliced[indice] wine
indice =  7
sliced[indice] Line  <-- *WHY IS THIS NOT CONSIDERED EQUAL TO "line"?*
indice =  8
sliced[indice] up
indice =  9
sliced[indice] now
indice =  10
sliced[indice] behind
indice =  11
sliced[indice] the
indice =  12
sliced[indice] cow
scat exdented:  12
frequence:  1
podium:  [1, 1, 1, 1]
'''

这是我的问题:

项目“line”在列表中出现了 2 次,我确信 scat=11frequence = 2

我尝试过许多不同的缩进,但主要的兴趣在于我没有能力遵循程序向机器发出的操作指令。

为了说明这一点,我尝试打印许多步骤,但我确实需要进一步说明。请帮忙。

Python 字符串比较区分大小写。所以 'A' == 'a'False。如果你想做不区分大小写的比较,你应该使用 lowerupper 方法来使字符串小写或大写。所以 'A'.lower() == 'a'True.

在您的情况下,由于它们是多字符字符串,因此您希望在两者上都使用 lower,例如 sliced[indice].lower() == item.lower()。您还可以在开始之前将整个列表转换为小写,从而完全避免该问题,如下所示:

slicedlow = [item.lower() for item in sliced]

但是,您可以使用 collections.Counter 对象将整个算法转换为几行:

from collections import Counter
slicedlow = [item.lower() for item in sliced]
counts = Counter(slicedlow)
maxcount = max(counts.values())

甚至一行:

from collections import Counter
maxcount = max(Counter(item.lower() for item in sliced).values())