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

如何读取字典中H5文件列表并赋值为指定变量?

批量读取H5文件并创建对应变量的解决方案

原始输入字典

input_dict = {'Sample': ['org_1', 'org_2', 'org_3'], 
              'Location': ['../cellbender/SAM24425933_cellbender_out_filtered.h5', 
                           '../cellbender/SAM24425932_cellbender_out_filtered.h5',
                           '../cellbender/SAM24425934_cellbender_out_filtered.h5']
                           }

需求

创建变量org_1、org_2、org_3,分别对应读取上述字典中Location列表里对应路径的H5文件对象。

错误代码及报错信息

尝试的代码:

for sample, location in input_dict.items():
    adata = sc.read_hdf(filename = location, key = sample)

报错:

TypeError: expected str, bytes or os.PathLike object, not list

错误原因

input_dict.items()会遍历字典的键值对,每次迭代得到的是('Sample', ['org_1', 'org_2', 'org_3'])和('Location', [路径1, 路径2, 路径3])。也就是说,循环里的location是整个路径列表,而sc.read_hdf的filename参数需要单个字符串路径,因此触发类型错误。

正确实现方法

方法一:直接创建全局变量(满足需求,但不推荐大量使用)

import scanpy as sc

input_dict = {'Sample': ['org_1', 'org_2', 'org_3'], 
              'Location': ['../cellbender/SAM24425933_cellbender_out_filtered.h5', 
                           '../cellbender/SAM24425932_cellbender_out_filtered.h5',
                           '../cellbender/SAM24425934_cellbender_out_filtered.h5']
                           }

# 将样本名与对应路径一一配对遍历
for sample_name, file_path in zip(input_dict['Sample'], input_dict['Location']):
    # 在全局命名空间创建以样本名为名的变量
    globals()[sample_name] = sc.read_hdf(filename=file_path, key='data')

注意:key参数需要根据H5文件内实际存储的键调整,比如部分文件用'X'或其他键,需自行核对。

方法二:用字典存储对象(更规范,便于管理)

如果不需要单独的变量名,推荐用字典统一存储所有读取的对象,避免命名空间混乱:

import scanpy as sc

input_dict = {'Sample': ['org_1', 'org_2', 'org_3'], 
              'Location': ['../cellbender/SAM24425933_cellbender_out_filtered.h5', 
                           '../cellbender/SAM24425932_cellbender_out_filtered.h5',
                           '../cellbender/SAM24425934_cellbender_out_filtered.h5']
                           }

adata_collection = {}
for sample_name, file_path in zip(input_dict['Sample'], input_dict['Location']):
    adata_collection[sample_name] = sc.read_hdf(filename=file_path, key='data')

# 访问示例:adata_collection['org_1']

内容的提问来源于stack exchange,提问作者Carmen Sandoval

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:40:20