你想要的就是所谓的直方图。有了直方图之后,打印满足条件的数字很容易。
有几种创建直方图的方法。让我们假设我们定义这个名单:如果您的Python> = 2.5,则可以使用defaultdict()
简化环路这两行
list_ = [1,1,2,3,4,4,4,5,6]
用手
histogram = {}
for i in list_:
oldfreq = histogram.get(i, 0) # get the old number of times we've seen i, or 0 if we haven't seen it yet
histogram[i] = oldfreq+1 # add one to the old count
defaultdict
from collections import defaultdict
histogram = defaultdict(int) # this means, "if we haven't seen a number before, set its default value to the result of int(), which is 0
for i in list_:
histogram[i] += 1
如果你的Python> = 2.7,则可以使用Counter
,对于直方图制作这是特制
计数器
from collections import Counter
histogram = Counter(list_)
现在,你有你的直方图,可以过滤它来获得只有那些不止一次出现的数字。
twoormore = [n for n,freq in histogram.iteritems() if freq > 1]
print twoormore
你试过了吗? '而v == 1:'将失败,因为'v'没有被定义... – dhg
他们会以某种方式找到数字在哪里彼此接近?所以它会说,如果列表中的2个数字是.0001的差异打印该数字? – Shantanu