【问题标题】:return and print in python在python中返回并打印
【发布时间】:2017-08-21 14:57:06
【问题描述】:

如何在 python 中返回函数 print() 的输出?我有以下功能

def read_image(raw_image_path):
    raw_image_path = get_one_track()
    with open (raw_image_path) as raw_image_file:
        content = raw_image_file.readlines()
        for content in itertools.islice(content,1,len(content)):
            image_id = content.split()[0]   
            driver_id = content.split()[2]
            camera_spec = content.split()[1] + content.split()[2]
            image_spec = [image_id,driver_id,camera_spec]

            image_folder_file = read_img_folders_file()[0]
            cam_spec=read_img_folders_file()[1]
            nb = read_img_folders_file()[2]
            image_path=''
            for i in range(nb-1):
            if cam_spec[i]== image_spec[2]:
                image_path=image_folder_file[i]+'/'

            raw_image= image_path+str(image_id).zfill(10)+'.png' 
            #print (raw_image)
            return (raw image)

问题是当我使用 print (raw_image) 时,我变成了我需要的所有图像

/home/stereo_front_left/0000001756.png
/home/stereo_front_left/0000001757.png
/home/stereo_front_left/0000001758.png

但是当我尝试在函数之外获取它们时,我只是第一个。我能做些什么?

【问题讨论】:

  • print() 终止函数,使用yield raw_image,然后在执行函数时使用print(list(read_image(raw_image_path)))
  • @Chris_Rands:我想你的意思是:“return 终止函数。”
  • @Chris_Rands“打印终止函数”?从什么时候开始?
  • @khelwood Matthias 确实,我的意思是 return 当然,对造成的任何混淆表示歉意

标签: python python-2.7 printing return


【解决方案1】:

如果您想将所有 raw_image 放在循环之外,则需要将它们存储在列表或某处,然后编写“return all_raw_images”。

    all_raw_images = []
    for content in itertools.islice(content,1,len(content)):
            image_id = content.split()[0]   
            driver_id = content.split()[2]
            camera_spec = content.split()[1] + content.split()[2]
            image_spec = [image_id,driver_id,camera_spec]

            image_folder_file = read_img_folders_file()[0]
            cam_spec=read_img_folders_file()[1]
            nb = read_img_folders_file()[2]
            image_path=''
            for i in range(nb-1):
                if cam_spec[i]== image_spec[2]:
                    image_path=image_folder_file[i]+'/'

            raw_image= image_path+str(image_id).zfill(10)+'.png' 
            all_raw_images.append(raw_image)

    return (all_raw_images)

【讨论】:

    【解决方案2】:

    你不需要让 print() 返回。

    它是一个函数,而不是一个方法,所以它会自动返回。

    抱歉,如果我误解了您的问题。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多