小能豆

我怎样才能将像这样的字典列表转换[{'a':1}, {'b':2}, {'c':1}, {'d':2}]为像这样的单个字典{'a':1, 'b':2, 'c':1, 'd':2}?

javascript

我怎样才能将像这样的字典列表转换[{‘a’:1}, {‘b’:2}, {‘c’:1}, {‘d’:2}]为像这样的单个字典{‘a’:1, ‘b’:2, ‘c’:1, ‘d’:2}?


阅读 57

收藏
2024-07-27

共1个答案

小能豆

使用 start() 和 stop() 控制:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

用法:

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

特征:

  • 仅限标准库,无外部依赖
  • start()``stop()即使计时器已启动/停止,也可以安全地多次调用
  • 被调用的函数可以有位置参数和命名参数
  • 您可以interval随时更改,它将在下次运行后生效。argskwargs甚至 也一样function
2024-07-27