【问题标题】:Python: Simplify variable declaration (with a for loop ?)Python:简化变量声明(使用 for 循环?)
【发布时间】:2021-08-25 05:09:06
【问题描述】:

我是 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')

感谢您的帮助

【问题讨论】:

标签: python for-loop variables declaration


【解决方案1】:

使用字典:

Left = {i: PhotoImage(file = 'image_'+str(i)+'.jpg') for i in range(1,11)}

并通过Left[7]访问

【讨论】:

    【解决方案2】:

    这基本上是@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...

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多