【发布时间】:2018-08-06 13:51:40
【问题描述】:
我有一个排序列表,我想在不使用count() 函数的情况下计算每个数字出现的次数。
sameItem = 0
startPosition = 1
sortedList = [13, 15, 15, 17, 18, 18, 18, 18, 19, 20, 20, 20, 20, 21, 22, 22, 22, 22, 23, 23, 23, 24, 24, 26, 26, 26, 27, 27, 27, 28]
for i in range(1, len(sortedList)):
item1 = sortedList[i - 1]
item2 = sortedList[i]
countItems = 1
sameItem = countItems
if item1 == item2:
startPosition = i
while (sortedList[i - 1] == sortedList[startPosition]):
sameItem += 1
startPosition += 1
else:
sameItem = countItems
print(str(item1) + " appears " + str(sameItem) + " times")
【问题讨论】:
-
你有什么问题?
-
一种方法是创建一个计数器数组并使其成为最大数的大小。所以在你的情况下 int countArray[29];现在您可以执行类似 countArray[13]++ 的操作来计算 13 出现的次数。然后将countArray的值相加。
-
这可能会对您有所帮助。 Count occurrence in sorted array
标签: python-3.x count