检查列表中的值是否相等 ~Python
我在想有没有办法查看列表中相似的值。比如说,如果列表中有两个数字是相等的,就打印出这个数字。谢谢大家的帮助。
补充说明:我在想这样做是否可行。
a = []
v = 0
while v == 1:
n = x - (func1sub/func1dsub)
a.append(n)
print (a)
d = defaultdict(int)
for v in a:
d[v] += 1
print (v)
3 个回答
1
这是我的一个变种:
In [12]: a = [1,1,2,3,4]
In [13]: z = set([(val,a.count(val)) for val in a])
In [14]: z
Out[14]: set([(1, 2), (3, 1), (4, 1), (2, 1)])
2
>>> from collections import defaultdict
>>> l = [1,2,2,3]
>>> d = defaultdict(int)
>>> for v in l:
... d[v] += 1
...
>>> d
defaultdict(<type 'int'>, {1: 1, 2: 2, 3: 1})
>>> [v for (v,c) in d.iteritems() if c > 1]
[2]
所以,2
是唯一一个出现超过一次的值。
需要注意的是,这种方法的时间复杂度是线性的,因为它只需要遍历一次列表来建立字典。如果对列表中的每个项目都调用count
,那样的时间复杂度就是平方级别的。
2
你想要的东西叫做直方图。得到直方图后,打印出满足你条件的数字就简单多了。
创建直方图有几种方法。假设我们有这样一个列表:
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
如果你使用的是Python 2.5及以上版本,可以用defaultdict()
来简化循环中的两行代码。
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
,这是专门为创建直方图设计的工具。
Counter
from collections import Counter
histogram = Counter(list_)
现在你有了直方图,可以对它进行筛选,只保留那些出现超过一次的数字。
twoormore = [n for n,freq in histogram.iteritems() if freq > 1]
print twoormore