繁体   English   中英

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

[英]Create if-elif statements using 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])

也许是这样的:

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)

试试这个方法:

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}")

使用字典:

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语句:)

就个人而言,当我知道这个长度时,我会去找一些功能性的东西:

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)

这似乎工作:

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))])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM