Python:简化变量声明(使用 for 循环?)
Python: Simplify variable declaration (with a for loop ?)
我是 python 的新手,我在我的代码中声明了一些变量,但它们几乎相似,我想知道是否可以使用 for
循环来简化它等等,以免有10行声明?
Left_10 = PhotoImage(file = 'image_10.jpg')
Left_9 = PhotoImage(file = 'image_9.jpg')
Left_8 = PhotoImage(file = 'image_8.jpg')
Left_7 = PhotoImage(file = 'image_7.jpg')
Left_6 = PhotoImage(file = 'image_6.jpg')
Left_5 = PhotoImage(file = 'image_5.jpg')
Left_4 = PhotoImage(file = 'image_4.jpg')
Left_3 = PhotoImage(file = 'image_3.jpg')
Left_2 = PhotoImage(file = 'image_2.jpg')
Left_1 = PhotoImage(file = 'image_1.jpg')
感谢您的帮助
使用字典:
Left = {i: PhotoImage(file = 'image_'+str(i)+'.jpg') for i in range(1,11)}
并使用 Left[7]
访问
这基本上是@Julien 所说内容的副本,但作为 list
而不是 dict
:
Left = [PhotoImage(file=f"image_{i}.jpg") for i in range(1, 11)]
并且您可以通过索引访问它们并对其进行排序(与 dict
不同):
Left[0] # PhotoImage with file=image_1.jpg
...
我是 python 的新手,我在我的代码中声明了一些变量,但它们几乎相似,我想知道是否可以使用 for
循环来简化它等等,以免有10行声明?
Left_10 = PhotoImage(file = 'image_10.jpg')
Left_9 = PhotoImage(file = 'image_9.jpg')
Left_8 = PhotoImage(file = 'image_8.jpg')
Left_7 = PhotoImage(file = 'image_7.jpg')
Left_6 = PhotoImage(file = 'image_6.jpg')
Left_5 = PhotoImage(file = 'image_5.jpg')
Left_4 = PhotoImage(file = 'image_4.jpg')
Left_3 = PhotoImage(file = 'image_3.jpg')
Left_2 = PhotoImage(file = 'image_2.jpg')
Left_1 = PhotoImage(file = 'image_1.jpg')
感谢您的帮助
使用字典:
Left = {i: PhotoImage(file = 'image_'+str(i)+'.jpg') for i in range(1,11)}
并使用 Left[7]
这基本上是@Julien 所说内容的副本,但作为 list
而不是 dict
:
Left = [PhotoImage(file=f"image_{i}.jpg") for i in range(1, 11)]
并且您可以通过索引访问它们并对其进行排序(与 dict
不同):
Left[0] # PhotoImage with file=image_1.jpg
...