冷凝大型Unpythony if语句

时间:2013-09-25 15:14:36

标签: python if-statement for-loop

我有很多,如果elif else声明工作得很好......他们似乎非常愚蠢,我将要加倍我需要的数字。基本上我正在为一个图形的x值的数量进行用户输入,通过数据分类器发送它并绘制图形。为简单起见,我只是将x = 1(min)和x = 6(max)值,但我想添加'多少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循环,但我不知所措,所以我不知道从哪里开始。一切都运作良好。它看起来很混乱

5 个答案:

答案 0 :(得分:1)

输入部分可以通过使其保留六个列号的列表而不是六个单独的变量来重写:

howManyX = int(raw_input('Input number of x-values for this graph: '))

x_col_nums = [1] * 6
for i in range(howManyX):
    x_col_nums[i] = int(raw_input("Input column number for x%d-value: " % (i + 1)))

然后简单地将整个第二个块放入for循环中:

for x1 in x_col_nums:
    # all your second block of code goes here
    # you might want to change the variable name x1 to just be x, which might
    # make it clearer

要保存x(n)Axis之类的变量,以便以后可以使用它们,请保留这些变量的列表,方法是:

xaxes = []
在循环之前

并添加行

    xaxes.append(x1Axis)

在循环中。之后,您可以访问过去的x1Axisx2Axis ...作为xaxes[0]xaxes[1]等等。

答案 1 :(得分:0)

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 = x3 = x4 = x5 = = x6 = 1

elif howManyX == 6:
    x1, x2, x3, x4, x5, x6 = (
        int(raw_input("Input column number for x{}-value: ".format(i)))
        for i in range(1, 7)
    )

答案 2 :(得分:0)

您可以将每个xN变量转换为某个数组中的等效变量。例如xs ...虽然你应该在它之后命名它,而不仅仅是x

第一部分将是:

howManyX = int(raw_input('Input number of x-values for this graph: '))
xs = [1]*howManyX
for i in range(howManyX):
    xs[i] = int(raw_input("Input column number for x%i-value: " % (i+1)))

当然另一个块也需要更新变量。如果您使用不同x之间的变量,则可以执行xAxes[i],或者如果它们只是单个x的本地变量,请完全删除该数字。

答案 3 :(得分:0)

您可以让用户输入他们感兴趣的值(让我们以dict的形式说出来)并对其进行评估。这样他们就可以指定第7列和第12列,而不用担心其他人...如果您愿意,可以使用max(vals)获取引用的最高列...(或者您的key->值对关系是定义)

from ast import literal_eval

# User enters something like: { 1:3, 5: 2}
vals = literal_eval(raw_input()) 
if not isinstance(vals, dict):
    # Uh oh... maybe do something here?
# Then use (to get columns, or 1 or whatever if not entered)
col_val3 = vals.get(3, 1)

答案 4 :(得分:-1)

您使用太多变量而不是数组。您可以使用for循环和数组x

x = [None]*howManyX
for i in range(howManyX):
    x[i] = int(raw_input("Input column number for x%d-value: " % (i+1)))

在特定情况下,您可以设置返回类变量(使用内置setattr),或者在简单脚本的情况下,您甚至可以设置全局变量(如果您确实需要):

scope = globals()   # in case of simple script
scope = self.__dict__
for i, val in enumerate(x):
   scope["x%d" % (i+1)] = val