我有一个排序列表,我想不使用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")
答案 0 :(得分:1)
您可以使用itertools.groupby
:
from itertools import groupby
for k, g in groupby(sortedList):
print('%s appears %d times' % (k, len(list(g))))
或者,如果您不想使用任何库函数:
count = 1
for i, n in enumerate(sortedList):
if i == len(sortedList) - 1 or n != sortedList[i + 1]:
print('%s appears %d times' % (n, count))
count = 1
else:
count += 1
或者,如果您根本不想使用任何功能(实际上print
也是一个功能,但我认为您不能不使用它)
last = None
for n in sortedList:
if n != last:
if last is not None:
print('%s appears %d times' % (last, count))
last = n
count = 1
else:
count += 1
print('%s appears %d times' % (last, count))
以上所有输出:
13 appears 1 times
15 appears 2 times
17 appears 1 times
18 appears 4 times
19 appears 1 times
20 appears 4 times
21 appears 1 times
22 appears 4 times
23 appears 3 times
24 appears 2 times
26 appears 3 times
27 appears 3 times
28 appears 1 times
答案 1 :(得分:0)
i = 1
check = False
sameItem = 0
while(i if sortedList[i-1] == sortedList[i]:
check = True
j = i
while (sortedList[i-1] == sortedList[j]) and (check == True):
sameItem += 1
j += 1
if (sortedList[i-1] != sortedList[j]):
check = False
i = j
print(str(sortedList[i-1]) + " appears " + str(sameItem) + " times")
else:
sameItem = 1
print(str(sortedList[i-1]) + " appears " + str(sameItem) + " times")
i += 1