【问题标题】:can this list enumerate method be shorter? or more pythonic?这个列表枚举方法可以更短吗?还是更蟒蛇?
【发布时间】:2020-10-03 17:16:40
【问题描述】:

我想看看能不能让下面的代码更简洁一些?更短?作为一种学习方式。谢谢。
重点代码是这一行:

for i, (x, y) in enumerate(zip (self.labelVariable_list,self.monday_results)): 
    self.labelVariable_list[i].set(self.monday_results[i])

原代码:

    for r in range(12):
        self.labelVariable=tk.StringVar()
        self.label = tk.Label(self, textvariable=self.labelVariable, borderwidth=1, relief="solid", width=9, height=1)
        self.label.grid(row=r+1, column=1)
        self.labelVariable_list.append(self.labelVariable)

    self.labelVariable_list[0].set(self.monday_results[0])
    self.labelVariable_list[1].set(self.monday_results[1])
    self.labelVariable_list[2].set(self.monday_results[2])
    self.labelVariable_list[3].set(self.monday_results[3])
    self.labelVariable_list[4].set(self.monday_results[4])
    self.labelVariable_list[5].set(self.monday_results[5])
    self.labelVariable_list[6].set(self.monday_results[6])
    self.labelVariable_list[7].set(self.monday_results[7])
    self.labelVariable_list[8].set(self.monday_results[8])
    self.labelVariable_list[9].set(self.monday_results[9])
    self.labelVariable_list[10].set(self.monday_results[10])
    self.labelVariable_list[11].set(self.monday_results[11])

我做到了:

    for r in range(12):
        self.labelVariable=tk.StringVar()
        self.label = tk.Label(self, textvariable=self.labelVariable, borderwidth=1, relief="solid", width=9, height=1)
        self.label.grid(row=r+1, column=1)
        self.labelVariable_list.append(self.labelVariable)

    for i, (x, y) in enumerate(zip (self.labelVariable_list, self.monday_results)):
        self.labelVariable_list[i].set(self.monday_results[i])

再次感谢您的 cmets。

【问题讨论】:

    标签: python-3.x list merge zip enumerate


    【解决方案1】:

    您可以尝试这样的列表理解:

    [list_1[i].set(list_2[i]) for i, (l1, l2) in enumerate(zip(list_1, list_2))]
    

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2014-02-13
      • 2011-11-16
      相关资源
      最近更新 更多