这是一段代码,在底部,在代码的'''注释部分''中,有一条线让我感到惊讶。请看一下:
#!/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=11
和frequence = 2
。
我尝试了很多不同的缩进词,但主要的兴趣是我没有能力按照程序命令到机器的操作过程。
为了说明这一点,我试图打印许多步骤,但我真的可以使用一些进一步的说明。请帮忙。
答案 0 :(得分:0)
Python字符串比较区分大小写。所以'A' == 'a'
是False
。如果要进行不区分大小写的比较,则应使用lower
或upper
方法将字符串设置为大写或小写。因此'A'.lower() == 'a'
为True
。
在您的情况下,由于它们是多字符字符串,您可能希望在两者上使用较低字符串,例如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())