You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取BED文件存入字典重复键覆盖问题的解决方案咨询

方案合理性说明
  • 你提到的给key加序号后缀的方案可正常实现,但并非最优选择:
    • 该结构后续按染色体批量查询区间时,需要遍历匹配key前缀,使用成本更高
    • 更推荐的存储结构是用染色体编号作为key,值为该染色体所有[start, end]区间组成的列表,符合BED文件按染色体归类的常见使用场景
  • 如果你确实需要保留每条记录对应独立key的结构,也可以按你提出的后缀方案实现

代码实现

更优的归类存储方案

def load_data(self):
    '''
    从BED文件加载数据,按染色体分组存储
    '''
    chr2position = {}
    with open(self.file_path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            if line.startswith(('chr',"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","Y","X")):
                cols = line.split()
                chr_name, start, end = cols[0], int(cols[1]), int(cols[2])
                # 染色体首次出现时初始化空列表
                if chr_name not in chr2position:
                    chr2position[chr_name] = []
                chr2position[chr_name].append([start, end])
    return chr2position

返回值示例:

{'chr7': [[127477031, 127478198], [127478198, 127479365], [127479365, 127480532]], 'chr8': [[127480532, 127481699], [127474697, 127475864]]}

带序号后缀的key方案

def load_data(self):
    '''
    从BED文件加载数据,每条记录对应带行号后缀的独立key
    '''
    chr2position = {}
    # 记录每个染色体的行计数
    chr_counter = {}
    with open(self.file_path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            if line.startswith(('chr',"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","Y","X")):
                cols = line.split()
                chr_name, start, end = cols[0], int(cols[1]), int(cols[2])
                # 更新对应染色体的行计数
                if chr_name not in chr_counter:
                    chr_counter[chr_name] = 0
                new_key = f"{chr_name}_line{chr_counter[chr_name]}"
                chr2position[new_key] = [start, end]
                chr_counter[chr_name] += 1
    return chr2position

返回值完全符合你要求的chrN_lineX格式的key结构。


内容的提问来源于stack exchange,提问作者Manolo Dominguez Becerra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:45:03