脚本如何统计重复数据次数

wen 实用脚本 28

本文目录导读:

脚本如何统计重复数据次数

  1. Python 统计列表重复数据
  2. Shell 脚本统计文本中的重复行
  3. SQL 统计数据库中的重复数据
  4. JavaScript 统计数组重复
  5. Excel/Google Sheets 统计重复
  6. 高级应用:统计并输出详细信息
  7. 选择建议

Python 统计列表重复数据

基础方法(使用字典)

def count_duplicates(items):
    count_dict = {}
    for item in items:
        if item in count_dict:
            count_dict[item] += 1
        else:
            count_dict[item] = 1
    # 只返回重复的项(出现次数 > 1)
    duplicates = {k: v for k, v in count_dict.items() if v > 1}
    return duplicates
# 示例
data = [1, 2, 3, 2, 1, 4, 5, 2, 3, 1]
result = count_duplicates(data)
print(result)  # {1: 3, 2: 3, 3: 2}

使用 collections.Counter

from collections import Counter
data = [1, 2, 3, 2, 1, 4, 5, 2, 3, 1]
counter = Counter(data)
duplicates = {k: v for k, v in counter.items() if v > 1}
print(duplicates)  # {1: 3, 2: 3, 3: 2}

Shell 脚本统计文本中的重复行

统计文件中的重复行

#!/bin/bash
# 统计文件中每行出现的次数
cat data.txt | sort | uniq -c | sort -rn
# 只显示重复的行(出现次数大于1)
cat data.txt | sort | uniq -c | sort -rn | awk '$1 > 1 {print $0}'

统计特定字段的重复

#!/bin/bash
# 统计 CSV 文件中第一列的重复值
cut -d',' -f1 data.csv | sort | uniq -c | sort -rn | awk '$1 > 1 {print $2, "出现", $1, "次"}'

SQL 统计数据库中的重复数据

基础统计

-- 统计某列的重复次数
SELECT column_name, COUNT(*) as count
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1
ORDER BY count DESC;

统计多列组合的重复

-- 统计多列组合的重复
SELECT col1, col2, COUNT(*) as count
FROM table_name
GROUP BY col1, col2
HAVING COUNT(*) > 1
ORDER BY count DESC;

JavaScript 统计数组重复

function countDuplicates(arr) {
    const countMap = {};
    const duplicates = {};
    arr.forEach(item => {
        countMap[item] = (countMap[item] || 0) + 1;
    });
    Object.keys(countMap).forEach(key => {
        if (countMap[key] > 1) {
            duplicates[key] = countMap[key];
        }
    });
    return duplicates;
}
// 示例
const data = [1, 2, 3, 2, 1, 4, 5, 2, 3, 1];
console.log(countDuplicates(data)); // {1: 3, 2: 3, 3: 2}

Excel/Google Sheets 统计重复

使用 COUNTIF 函数

=COUNTIF(A:A, A2)

然后筛选出计数大于1的行。

使用数据透视表

  1. 选择数据范围
  2. 插入数据透视表
  3. 将字段拖到行标签和值区域
  4. 值区域设置为计数

高级应用:统计并输出详细信息

Python 示例:统计并输出行号

def count_duplicates_with_lines(items):
    from collections import defaultdict
    line_records = defaultdict(list)
    for idx, item in enumerate(items, 1):
        line_records[item].append(idx)
    duplicates = {}
    for item, lines in line_records.items():
        if len(lines) > 1:
            duplicates[item] = {
                'count': len(lines),
                'lines': lines
            }
    return duplicates
# 示例
data = ['a', 'b', 'a', 'c', 'b', 'a']
result = count_duplicates_with_lines(data)
for item, info in result.items():
    print(f"'{item}': 出现 {info['count']} 次,在行号 {info['lines']}")
# 输出:
# 'a': 出现 3 次,在行号 [1, 3, 6]
# 'b': 出现 2 次,在行号 [2, 5]

选择建议

场景 推荐方法
小数据量 Python 处理 collections.Counter
大数据文件处理 Shell 脚本(sort + uniq)
数据库数据处理 SQL GROUP BY + HAVING
前端数据处理 JavaScript Map 或 Object
Excel 表格处理 COUNTIF 或数据透视表

需要我详细介绍某种特定场景的实现吗?

抱歉,评论功能暂时关闭!