简体   繁体   English

Python:使用循环语句将图像分配给变量

[英]Python : Assigning image to a variable using loop statement

I need to assign a image to three variables ie dsp1, dsp2, dsp3 by looping. 我需要通过循环将图像分配给三个变量,即dsp1,dsp2,dsp3。 On execution, I get a Syntax error. 执行时,出现语法错误。

SyntaxError: can't assign to operator. SyntaxError:无法分配给运算符。

for i in range(0,3):    
    dsp+str(i)=Image.open("L1.jpg")

What is the problem with 'str(i)' ? 'str(i)'是什么问题?

Can any one explain with simple example ? 有人可以用简单的例子解释吗?

You can not assign to an operator. 您不能分配给操作员。

Look at your code line: 查看您的代码行:

 dsp + str(i)  =  Image.open("L1.jpg")

You have dsp + str(i) on the left side, an expression containing the sum operator + . 左侧有dsp + str(i) ,一个包含sum运算符+的表达式。 Even if that would get evaluated properly, the result would be a string like "dsp1" for example. 即使可以正确评估,结果仍将是例如"dsp1"的字符串。 You can't assign any value to a string. 您不能将任何值分配给字符串。

And because such uses make no sense, Python does not support operators on the left side of an assignment. 而且因为这样的用法没有意义,所以Python不支持分配左侧的运算符。

You want to dynamically create a variable name instead of hard-coding it. 您要动态创建变量名,而不是对其进行硬编码。 Although this is possible using exec() , that is strongly discouraged, as it easily leads to bugs in your code, is hard to read and even harder to debug. 尽管可以使用exec()做到这一点,但强烈建议不要这样做,因为它很容易导致代码中的错误,难以阅读,甚至难以调试。 It may even be a security risk (code injection) if anything getting evaluated this way is untrusted data like user input. 如果以这种方式评估的任何内容都是不受信任的数据(例如用户输入),则甚至可能存在安全风险(代码注入)。

What you should use instead is a simple list : 您应该使用的是一个简单的list

dsp = []
for i in range(0,3):    
    dsp[i] = Image.open("L1.jpg")  # for whatever reason you open the same file 3 times...

You create a list simply using the square brackets. 您只需使用方括号即可创建列表。 If you want to initialize it with some values, simply write them inside, separated by commas: 如果要使用一些值初始化它,只需将它们写在里面,并用逗号隔开:

my_list = ["zero", 1, 2, "three", 4.5, True]

You access elements of a list by specifying an index value, starting with 0 for the first element: 通过指定索引值来访问列表的元素,第一个元素从0开始:

print(my_list[3])  # output: three

You can also easily loop over all elements of a list: 您还可以轻松地遍历列表的所有元素:

for item in my_list:
    print(item)
# output:
# zero
# 1
# 2
# three
# 4.5
# True

Instead of generating dynamic variables, place these images in a list: 代替生成动态变量,将这些图像放在列表中:

images = []
for i in range(3):
    images[i] = Image.open("L1.jpg")

Using this method, the L1.jpg is assigned to the following: 使用此方法, L1.jpg被分配给以下内容:

images[0]
images[1]
images[2]

Alternatively, you can use a dictionary to get closer to the variable name format you are using: 另外,您可以使用字典来更接近所使用的变量名格式:

images = {}
for i in range(3):
    images['dsp' + str(i)] = Image.open("L1.jpg")

This produces a dictionary that has the following layout: 这将产生具有以下布局的字典:

{
'dsp2': <image object>, 
'dsp1': <image object>, 
'dsp0': <image object>
}

You can access any of these images by using the key (ie. image['dsp1'] ) 您可以使用键访问任何这些图像(即image['dsp1']

In both of these cases, you don't need to worry about dynamic variables. 在这两种情况下,您都不必担心动态变量。 Instead, everything you will be using sits in either a single list or dictionary. 相反,您将要使用的所有内容都位于单个列表或词典中。

You can't just string text together to create a variable name like that unfortunately. 不幸的是,您不能只是将文本字符串串在一起来创建这样的变量名。 The problem is with dsp+str(i)= , not just str(i) . 问题出在dsp+str(i)= ,而不仅仅是str(i)

If you absolutely must do it this way, you can do it using globals like so: 如果您绝对必须以这种方式执行此操作,则可以使用globals来执行此操作,如下所示:

for i in range(0,3):    
    globals()["dsp" + str(i)] = Image.open("L1.jpg")

print(dsp1) # This will contain something

This will allow you to access those variables as if you had created them the 'normal' way first. 这将允许您访问这些变量,就像您首先以“常规”方式创建它们一样。

Ideally though, you should probably assign your results to a list instead, rather than discrete variable names. 不过,理想情况下,您应该将结果分配给list ,而不是离散变量名。

The problem is that you're trying to generate variable names on the fly. 问题是您试图动态生成变量名。 If I were you I would try to use a dictionary instead of generation dynamic variable names. 如果您是我,我将尝试使用字典而不是生成动态变量名称。 If you REALLY need dynamic variable names I would go for something like this: 如果您真的需要动态变量名,那么我会这样做:

exec("dsp%d = Image.open(\\"L1.jpg\\")" % (i)); exec(“ dsp%d = Image.open(\\” L1.jpg \\“)”%(i));

but I really do not recommend it. 但我真的不推荐。 Just use a dictonary! 只需使用字典即可​​!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM