使用for循环创建if-elif语句

时间:2013-06-30 06:42:31

标签: python if-statement for-loop

我正在处理一个涉及多个if和elif conditining的问题。我的情况如下:

if len(g) == 2:
   a = 'rea: 300'
   b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300}' % (g[0],g[1])

elif len(g) == 3:
   a = 'rea: 400'
   b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300},"%s": {"sds": 400}' % (g[0],g[1],g[2])
....

这个elif条件应该是elif len(g)== 99 ...所以我想应该有一些优雅的方法来做到这一点。此外,如果您观察到,有一种模式,'rea'和'ref'正在进行中,可以表示为:

 if len(g) == x:
    a = 'rea: (x*100)+100'
    b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300},"%s": {"sds": (x*100)+100}' % (g[0],g[1],g[2])

5 个答案:

答案 0 :(得分:2)

也许是这样的:

g_len = len(g)
a = "rea: {}".format((g_len + 1) * 100)
b = "ref: "
for i, g_i in enumerate(g):
    b += ' "{}": {{"sds": {}}},'.format(g_i, (i+2) * 100)

答案 1 :(得分:2)

试试这个方法:

def func(g):
    if not 1 < len(g) < 100:
        raise ValueError('inadequate length')
    d = {x:{'sds':(i+2)*100} for i, x in enumerate(g)}
    a = 'rea: %s00' % (len(g)+1)
    b = 'ref: %s' % str(d)[1:-1]
    return (a, b)

我不知道你为什么要创建一个看起来非常像字典的字符串b,但我相信你有理由......

>>> func(range(3))
('rea: 400', "ref: 0: {'sds': 200}, 1: {'sds': 300}, 2: {'sds': 400}")

答案 2 :(得分:0)

使用字典:

x = 100
d = {}
for i in xrange(2, len(g)+1):
    d[i] = ['rea: {}'.format(100+x*i), 'ref: '+ ('%s: {"sds": 200}, ' *(i-1) + ' %s: {"sds": 200}') % tuple(g[:i])]

现在,d看起来像:

{2: ['rea: 300',
     'ref: "depends_on_g": {"sds": 200}, "depends_on_g": {"sds": 300}'],
 3: ['rea: 400',
     'ref: "depends_on_g": {"sds": 200}, "depends_on_g": {"sds": 300}', "depends_on_g": {"sds": 300}]
 ...
}

然后,访问它:

a, b = d.get(len(g))

不需要if语句:)

答案 3 :(得分:-1)

就个人而言,当我知道长度如下时,我会选择功能性的东西:

def do_Condition(g):
    """ Condtion the result based on the length of g """
    l = len(g)
    a = 'rea: %d' % (100 + 100*l)
    items = ['ref: "%s"' % (g[0])]
    n = 100
    for i in g[1:]:
        n += 100
        items.append('{"sds": %d},"%s"' % (n, i))
    b = ': '.join(items)
    return (a, b)

答案 4 :(得分:-1)

这似乎有效:

a = 'rea: %d00' % (len(g)+1)
b = ",".join(['ref: "%s": {"sds": %d00}' % (i, j) for i, j in  zip(g, range(2,len(g)+2))])