3 3 3 这个是 3 个相等的数字了,这个不算
只能是 2 个数字相等,3 个数字相等不行
### python3.6
list = [1,3,8,9,15,12,15,3,3,9]
a = {} #定义空字典
for i in set(list): #去重复的值,set
a[i] = list.count(i) #去重后做计数,把数量和值写到字典a
if a[i]==2: #如果值等于2
print(i) #输出key
[k for k,v in Counter(testlist).items() if v == 2]
from collections import Counter
source = [1, 3, 8, 9, 15, 12, 15, 3, 3, 9]
# 不使用 python 标准库
def get_2dup(candidates):
if candidates is None:
return []
if len(candidates) <= 1:
return []
count_result = {}
for candidate in candidates:
count_result[candidate] = count_result.get(candidate, 0) + 1
return [k for k, v in count_result.items() if v == 2]
# 使用Counter
def get_2dup_counter(candidates):
if candidates is None:
return []
if len(candidates) <= 1:
return []
count_result = Counter(candidates)
return [k for k, v in count_result.items() if v == 2]
if __name__ == '__main__':
print(get_2dup(source))
print(get_2dup([1]))
print(get_2dup([]))
print(get_2dup(None))
print(get_2dup_counter(source))
print(get_2dup_counter(None))
print(get_2dup_counter([]))
print(get_2dup_counter([9]))
arr = [1,3,8,9,15,12,15,3,3,9]
d = {}
for i in arr:
if arr.count(i) == 2:
d[i] = '重复' + str(arr.count(i)) + '次'
print(d)
L = [1, 3, 8, 9, 15, 12, 15, 3, 3, 9]
print([i for i in set(L) if L.count(i)==2])
int [] arr = { 1,3,8,9,15,12,15,3,3,9};
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
count++;
}
}
if(count == 1) {
System.out.println(arr[i]+" ,");
}
}
def func(l):
d = dict()
for each in l:
if each not in d:
d[each] = 1
else:
d[each] += 1
new = [m for m,n in d.items() if n == 2]
return new
public static void main(String[] args) {
int array[]= new int[]{1,3,8,9,15,12,15,3,3,9};
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<array.length;i++){
if(map.containsKey(array[i])) {
map.put(array[i], map.get(array[i]) + 1);
} else {
map.put(array[i], 1);
}
}
for (HashMap.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue() == 2) {
System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue());
}
}
}
用 Counter
from collections import Counter
[k for k, v in Counter(a).items() if v == 2]
l=[1,3,8,9,15,12,15,3,3,9]
print([i for i in set(l) if l.count(i)==2])