每当我将某些内容添加到代码中先前定义的列表中时,我都希望打印某些内容。我该怎么做?
a = []
在Google上找不到与此有关的任何内容
答案 0 :(得分:5)
没有内置方法可以执行此操作,但是您可以非常轻松地使您的列表成为继承自list
的用户定义的类,并挂钩到append方法:
>>> class MyList(list):
...: def __init__(self, *args, **kwargs):
...: super().__init__(*args, **kwargs)
...:
...: def append(self, item):
...: print(f'item {item} will be appended to {str(self)}')
...: ret = super().append(item)
...: print(f'append succeeded -> list is now {str(self)}')
...: return ret
...:
>>> mylist = MyList('abc')
>>> mylist
['a', 'b', 'c']
>>> mylist.append('d')
item d will be appended to ['a', 'b', 'c']
append succeeded -> list is now ['a', 'b', 'c', 'd']
>>> mylist
['a', 'b', 'c', 'd']
我只是为了完成而添加了__init__
(以便它看起来更像传统类),但是您实际上只需要重新定义append
。
答案 1 :(得分:-1)
import time as t
list_ = []
while True:
original_len = len(list_)
t.sleep(0.01)
if len(list_) > original_len:
print('This list has obtained a new item')