def frequencies(data):
data.sort()
count = 0
previous = data[0]
print("data\tfrequency") # '\t' is the TAB character
for d in data:
if d == previous:
# same as the previous, so just increment the count
count += 1
else:
# we've found a new item so print out the old and reset the count
print(str(previous) + "\t" + str(count))
count = 1
previous = d
所以我有这个频率代码,但每次都会把列表中的最后一个数字去掉
这可能与我从上一个开始的位置有关,也可能与我在最后将上一个重置为d的位置有关
对于最后一组元素,您永远不会将它们打印出来,因为在打印之后您永远不会发现不同的内容。你需要在循环后重复打印输出
但这是相当学术的;在现实世界中,您更有可能使用
Counter
:可以使用
count
对列表/序列中的项进行计数。因此,您的代码可以简化为:相关问题 更多 >
编程相关推荐