python - 当属性不遵守命名规则时,Python 中的数据类

标签 python python-dataclasses

如果您有这样的数据(来自 yaml 文件):

items:
  C>A/G>T: "#string"
  C>G/G>C: "#string"
  ...

如何将其加载到明确其键和类型的数据类中? 理想情况下我会:

@dataclasses.dataclass
class X:
    C>A/G>T: str
    C>G/G>C: str
...

更新:

SBS_Mutations = TypedDict(
    "SBS_Mutations",
    {
        "C>A/G>T": str,
        "C>G/G>C": str,
        "C>T/G>A": str,
        "T>A/A>T": str,
        "T>C/A>G": str,
        "T>G/A>C": str,
    },
)

my_data = {....}

SBS_Mutations(my_data) # not sure how to use it here

最佳答案

如果你想要这样的符号,它们显然不能是Python标识符,然后,想要使用具有属性访问的数据类为你提供的设施是没有意义的。

只需将数据保存在字典或 Pandas 数据框中,这些名称可以是列标题。

否则,发布一个正确的代码片段,其中包含您从何处获取数据的最小示例,然后,人们可以添加答案,将您的原始名称翻译为正确的位置有效的 Python 属性名称,并帮助使用它构建动态数据类。

关于python - 当属性不遵守命名规则时,Python 中的数据类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72546423/

相关文章:

python - 通过链接 str.replace 方法替换字符会产生错误的结果

python - 在 Cython 中使用数据类

python - 如何将 marshmallow-dataclass 与 marshmallow-oneofschema 结合起来用于多态结构?

python - 使用 Python 实现负载均衡

python - 将Python字符串拆分为对列表

python - python是否使用其他方法保留注释顺序?

python - 无法导入数据类模块

python - 如何在数据类模块的 asdict 函数中使用枚举值

python - PyHook 未检测到某些窗口中按下的键

Pythonic 处理此错误情况