Python-记录字符串以前的内容

时间:2019-03-17 05:55:57

标签: python python-3.x

如果这是我的代码:

import matplotlib.pyplot as plt
plt.subplots(4, 1)
plt.subplots_adjust(hspace=0)
plt.subplot(411)
plt.xlabel('x (h)')
plt.ylabel(' y1 (nT)')
plt.minorticks_on()
plt.rcParams['xtick.bottom'] = True
plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = False
plt.plot(x,y1)
plt.subplot(412)
plt.xlabel('x (h)')
plt.ylabel(' y2 (nT)')
plt.minorticks_on()
plt.rcParams['xtick.bottom'] = True
plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = False
plt.plot(x,y2)
plt.subplot(413)
plt.xlabel('x (h)')
plt.ylabel(' y3 (nT)')
plt.minorticks_on()
plt.rcParams['xtick.bottom'] = True
plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = False
plt.plot(x,y3)
plt.subplot(414)
plt.xlabel('x (h)')
plt.ylabel(' y4 (nT)')
plt.minorticks_on()
plt.rcParams['xtick.bottom'] = True
plt.rcParams['xtick.labelbottom'] = True # I thought it will enable xtick labels only on the bottom x-axis of the last plot
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = False
plt.plot(x,y4)
plt.show()

我如何“记录” x = 1 x = 2 x = 3 过去的事物并打印它们?如果我的解释很愚蠢,那么这就是我的期望:

x

我该如何实现?

2 个答案:

答案 0 :(得分:4)

由于赋值会覆盖对象的值(在您的示例中为“ x”),因此无法完全执行所需的操作。但是,您可以创建一个对象,可以更改其值并记住其历史记录。例如这样的

#!/usr/bin/env/python3

class ValueWithHistory():

    def __init__(self):
        self.history = []
        self._value = None

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new_value):
        self.history.append(new_value)
        self._value = new_value

    def get_history(self):
        return self.history

    def clear_history(self):
        self.history.clear()


def main():
    test = ValueWithHistory()
    test.value = 1
    print(test.value)
    test.value = 2
    print(test.value)
    test.value = 3
    print(test.value)
    print(test.get_history())


if __name__ == '__main__':
    main()

此打印:

1
2
3
[1, 2, 3]

当然,例如,您也可以使用集合而不是列表来记住每个唯一值一次。

答案 1 :(得分:-2)

您可以命令第二个线程来观察字符串并打印更改:

OpenIdConnect.AuthenticationProperties=CfijlEY2jd9Jv4J7i5qy0K1ZZ5x2FR5ZraXo2dDVWl-a2RppU46kHpnoZe2mLJ2qpXFlpMRnu1nxKPYXepR4KwnhxAll88xSZmK41BsfIVkmCa34dfHK_RdBwRZW3cwHqIsD1N4Cqmr655xjK-gSr53zetwZeUq0UX-nBTpz1TZTgc64-8JOLiXPEVlvLM6KYZNQYGBkoCNCNCV_GEbgx0U1QuGPuHxglJD3SGbKF9bo_OjhI6L-U-hPbalY0Fa-

这将检查是否对字符串“ my_string”进行了操作并将其附加到列表“ log”(如果已更改)。有了这个,您应该可以执行

from threading import Thread
def string_watcher():
    global my_string
    global log
    temp = ''
    while True:
        if my_string != temp:
            log.append(my_string)
            temp = my_string

t = Thread(target=string_watcher, daemon=True)
t.start()

在运行时的任何时候