我有巨大的 if elif else 语句可以正常工作......它们看起来非常不合时宜,我即将增加一倍我需要的数量。基本上,我正在接受用户输入图表的 x 值数量,通过数据分类器发送它,然后绘制图表。为简单起见,我只输入 x=1(最小值)和 x=6(最大值)值,但我想添加“多少个 y?” 但我担心这会过于庞大和混乱。
有什么办法可以浓缩这个?
代码:
howManyX = int(raw_input('Input number of x-values for this graph: '))
if howManyX == 1:
x1 = int(raw_input("Input column number for x1-value: "))
x2 = 1
x3 = 1
x4 = 1
x5 = 1
x6 = 1
elif howManyX == 6:
x1 = int(raw_input("Input column number for x1-value: "))
x2 = int(raw_input("Input column number for x2-value: "))
x3 = int(raw_input("Input column number for x3-value: "))
x4 = int(raw_input("Input column number for x4-value: "))
x5 = int(raw_input("Input column number for x5-value: "))
x6 = int(raw_input("Input column number for x6-value: "))
下面这部分是相同的,除了 x1 是 x(n) 到 6。代码都是正确的,我只需要将 x1 更改为 x(1-6)
if x1 == 0:
x1a = sheet.col_values(x1)
x1b = [i for i in x1a if i != '']
x1c = [i for i in x1b if type(i) == float][1:]
x1Axis = [datetime.strptime(str(int(d)), '%Y%m%d') for d in x1c]
elif x1 == 31:
x1a = sheet.col_values(x1)
clear()
print "\n\n\n1: Top"
print "2. Bottom"
is_valid = 0
while not is_valid :
try :
choice = int ( raw_input('Enter your choice [1 or 2] : ') )
is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop
except ValueError, e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
if choice == 1:
x1Axis = filter(None, [i for i, j in zip(x1a, x1a[1:] + ['']) if j != ''])[1:]
elif choice == 2:
x1Axis = filter(None, [i for i, j in zip(x1a, x1a[1:] + ['']) if j == ''])[2:]
else:
print ("Invalid number. Try again...")
else:
x1a = sheet.col_values(x1)
x1Axis = filter(None, [i for i, j in zip(x1a, x1a[1:] + ['']) if j == ''])[2:]
看起来很多,那可能只是我的代码很乱。我认为它只需要一个简单的 for 循环,但我不知所措,所以我不知道从哪里开始。一切运作良好。只是看起来很乱