【问题标题】:way to attach context to a variable but not influence its effective value将上下文附加到变量但不影响其有效值的方法
【发布时间】:2020-12-10 20:20:27
【问题描述】:

我希望能够将上下文附加到字符串,但不是字符串值本身的一部分。

例子:

x = "leak"(gearbox)
y = "leak"(seal)

我希望以一种我仍然能够计算“泄漏”发生的次数但仍具有每次停留的上下文的方式来存储它。在这种情况下,“泄漏”发生了两次。

我需要能够将这些值存储在 pandas DataFrame 中,这样字典就不起作用了。

【问题讨论】:

  • 能否请您正确解释您的要求
  • 为什么不将它们存储在 df 的不同列中?

标签: python python-3.x string data-structures


【解决方案1】:

您可以继承collections.UserString 来保存自定义属性:

from collections import UserString

class MyString(UserString):
    def __init__(self, val, /, context=None):
        super().__init__(val)
        self.context = context

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多