当列表长度改变时执行代码行 Python

Execute line of code when length of list changes Python

当列表长度大于 1 时,我试图显示某段文本。

最初,当 streamlit 应用程序 运行 时,上传的图片列表中没有文件,所以我不想显示上传的图片文本,但是当有人上传图片时,我想显示“上传的图片: " 文字.

如何监听列表的长度并根据其变化执行代码。

我的代码:

uploaded_files = st.file_uploader(
    "Choose samples to upload...", accept_multiple_files=True)

image_list = []
image_captions = []

#ignore this function
def add_border(input_image, border, color=0):
    img = Image.open(input_image)
    if isinstance(border, int) or isinstance(border, tuple):
        bimg = ImageOps.expand(img, border=border, fill=color)
        return bimg
    else:
        raise RuntimeError('Border is not an integer or tuple!')


for uploaded_file in uploaded_files:
    image = add_border(uploaded_file, border=10, color='white')
    image_list.append(image)
    image_captions.append(uploaded_file.name)

if len(image_list) > 1:
    st.write("Uploaded Images :")


st.image(image_list, width=125)

这是我的想法:因为 image_list 将包含与 uploaded_files 中的图像一样多的图像,您可以简单地这样做:

count = 0 
for n, uploaded_file in enumerate(uploaded_files): 
   count += 1 
   # rest of ur code 

print("Uploaded Images:")