如何在python中附加print函数的值

时间:2017-03-11 20:10:22

标签: python python-2.7 list append

这就是打印功能给我的东西

/home/codes/paths/0000001090.png
/home/codes/paths/0000001091.png
/home/codes/paths/0000001092.png
/home/codes/paths/0000001093.png

我希望像

一样
[/home/codes/paths/0000001090.png
/home/codes/paths/0000001091.png
/home/codes/paths/0000001092.png
/home/codes/paths/0000001093.png]

所以我尝试使用list.append

raw_image_path= image_path+str(image_id).zfill(10)+'.png'
all_images = []   
all_images.append(raw_image_path)
print (all_images)

但它似乎分别追加每个印刷值

    [/home/codes/paths/0000001090.png]
    [/home/codes/paths/0000001091.png]
    [/home/codes/paths/0000001092.png]
    [/home/codes/paths/0000001093.png]

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

您似乎有一个循环,并且每次迭代都会创建并打印一个新列表。

for ...:
    raw_image_path= image_path+str(image_id).zfill(10)+'.png'
    all_images = []   # new list
    all_images.append(raw_image_path)
    print (all_images) # printing a single list
# 'len(all_images) == 1' here

选项:

1)在循环前将all_images移到外面,然后追加到内部,然后在外面打印

2)尝试列表理解。

In [1]: all_images = [ "{}{}.png".format('/', str(image_id).zfill(10)) for image_id in range(1090, 1095) ]

In [2]: all_images
Out[2]:
['/0000001090.png',
 '/0000001091.png',
 '/0000001092.png',
 '/0000001093.png',
 '/0000001094.png']