【发布时间】:2020-04-08 16:33:39
【问题描述】:
我正在尝试创建一个从目录加载某些图像的函数。条件是,如果图像名称包含某个数字,则应将其作为对象加载(带有名称和数字)。
这是我到目前为止所做的:
get_image_data([71,72,82,105...])
directory = os.listdir("/Users/Me/Desktop/path2images/")
#Sample of files
0070_pressure_pred.png
0070_pressure_target.png
0070_velX_pred.png
0070_velX_target.png
0070_velY_pred.png
0070_velY_target.png
0071_pressure_pred.png
0071_pressure_target.png
0071_velX_pred.png
0071_velX_target.png
0071_velY_pred.png
0071_velY_target.png
0072_pressure_pred.png
0072_pressure_target.png
0072_velX_pred.png
功能:
def get_pressure_prediction(file_numbers):
#takes a list of image number and returns them
for files in directory:
for x in file_numbers:
if str(x) in files[:4]:
print("File '{}' matched".format(files)) #Code functions fine until here
if str(pressure_pred) in files:
"pp{}".format(x) = mpimg.imread(path + files) #attempting to load image and label it with pp{image number}
elif str(pressure_target) in files:
"pt{}".format(x) = mpimg.imread(path + files)
elif str(velX_pred) in files:
"vxp{}".format(x) = mpimg.imread(path + files)
elif str(velX_target) in files:
"vxt{}".format(x) = mpimg.imread(path + files)
elif str(velY_pred) in files:
"vyp{}".format(x) = mpimg.imread(path + files)
elif str(velY_target) in files:
"vyt{}".format(x) = mpimg.imread(path + files)
break
我收到此错误消息:
"vyt{}".format(x) = mpimg.imread(path + files)
^
SyntaxError: can't assign to function call
【问题讨论】:
-
"vyt{}".format(x)这是一个格式化的字符串。你为什么要给它分配一些东西? -
@Axe319 我想给
mpimg.imread(path + files)一个标签 vyt(x)。结果应该是运行 get_image_data([71,72,82,105]) 应该给出 vyt71,vyt72,vyt82,vyt105。我不知道有任何其他方法可以为 vyt 和所有其他格式化字符串分配不同的数字。
标签: python python-3.x if-statement format-string