我仍然处于学习编程的“任何技术足够先进...”阶段。该代码似乎很笨拙,如果需要,很难更新。有没有更好的方法来解决这个问题?对我来说,它看起来简直是疯子,但它可以工作...对吗?
它从TKinter径向1-16中获取一个变量,并使用它选择grade1 ect变量。然后,将grade1变量链接到gspread上的工作表名称。
def go():
subject = v.get()
if subject == 1:
subject = grade1
elif subject == 2:
subject = grade2
elif subject == 3:
subject = grade3
elif subject == 4:
subject = grade4
elif subject == 5:
subject = grade5
elif subject == 6:
subject = grade6
elif subject == 7:
subject = grade7
elif subject == 8:
subject = grade8
elif subject == 9:
subject = grade9
elif subject == 10:
subject = grade10
elif subject == 11:
subject = grade11
elif subject == 12:
subject = grade12
elif subject == 13:
subject = grade13
elif subject == 14:
subject = grade14
elif subject == 15:
subject = grade15
elif subject == 16:
subject = grade16
答案 0 :(得分:9)
请勿为grade**
保留16个不同的变量!使用一个列表:
grades = [1, 2, 3, ...] # or whatever your values are
然后您要做的就是:
subject = grades[v.get() - 1]
答案 1 :(得分:2)
您可以将它们存储在grades=[grade1,...,grade16]
之类的列表中,然后将主题设置为subject = grades[v.get()-1]
答案 2 :(得分:1)
或使用字典:
d={1:grade1,2:grade2 ... 16:grade16}
print(d[v.get()])
您将获得理想的成绩。
您必须拥有一个字典,其中包含所有可能的v.get()
值的键以及每个键所需的等级值,因此,您需要在字典中获得v.get()
键,然后得到它值,通过使用d[v.get()]
,现在您已达到所需的成绩。
答案 3 :(得分:0)
解决它的方法很少。
# 1. Using the `list` data type
def go():
grade_list = [grade1, grade2, ... grade16]
subject = [grade_list[v.get() - 1]]
# 2. Using the `eval`
def go():
subject = v.get()
if subject in range(1, 17):
subject = eval("grade" + str(subject))
第一种方法被认为是更好的代码。但是,还有另一种使用方式
eval
关键字。它将内部代码视为表达式。由于仅变量的数字部分会更改。但是,eval
不是我推荐的最佳方法。有关更多信息,请参阅此页面Why is using 'eval' a bad practice?