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

如何在Snakemake中以惯用方式访问嵌套字典并传递文件路径?

在Snakemake中优雅提取嵌套字典中的文件路径作为规则输入

你在config.yml中定义了嵌套结构的实体配置:

entities:
    fbr:
        full_name: "FUBAR"
        filepath: "data/junk_1.txt"
    snf:
        full_name: "SNAFU"
        filepath: "data/junk_2.txt"

当前你通过列表推导式结合expand收集文件路径作为规则输入,但希望有更简洁的实现方式。以下是几种更惯用的优化方法:

方法1:移除冗余的expand,直接传入路径列表

expand用于根据通配符模板生成路径,这里你已经有完整的路径字符串,无需额外处理,直接传入列表即可:

configfile: "config.yml"

rule all:
    input:
        "data/result.txt"

rule first:
    input:
        [x["filepath"] for x in config["entities"].values()]
    output:
        "data/result.txt"
    shell:
        "cat {input} > {output}"

方法2:用operator.itemgetter简化字段提取

导入operator模块后,用map配合itemgetter可以更简洁地提取所有filepath字段:

from operator import itemgetter
configfile: "config.yml"

rule all:
    input:
        "data/result.txt"

rule first:
    input:
        list(map(itemgetter("filepath"), config["entities"].values()))
    output:
        "data/result.txt"
    shell:
        "cat {input} > {output}"

方法3:提前定义复用变量

如果多个规则需要用到这些文件路径,建议在Snakefile开头定义变量,后续直接引用即可:

configfile: "config.yml"
ENTITY_FILES = [ent["filepath"] for ent in config["entities"].values()]

rule all:
    input:
        "data/result.txt"

rule first:
    input:
        ENTITY_FILES
    output:
        "data/result.txt"
    shell:
        "cat {input} > {output}"

这些方法都能替代原有的繁琐写法,让代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:20:19