2017-03-03 178 views
0

验证码:怎样才能让这些代码3个系更加干燥

if len(group['elements']) > 0: 
    groups.append(group) 
    group = {'bla': '', 'elements': []} 

在下面的例子中重复3次。我想把它放在1行(至少使它减少)。有可能吗?那我该怎么做?

collection_of_items = [ 
    ['strong', 'a', ['a'], '', 'strong', ['a'], ['a'], 'a', 'a', [], ''], 
    ['strong', 'a', ['a'], '', 'strong', 'a'] 
] 

groups = [] 

for items in collection_of_items: 
    group = {'bla': '', 'elements': []} 
    for item in items: 
     if hasattr(item, 'lower'): 
      if item == 'strong': 
       group['bla'] = item 
      elif item =='a': 
       group['elements'].append(item) 
      elif item == '': 
       # Make it DRY <--------------------------------------- 
       if len(group['elements']) > 0: 
        groups.append(group) 
        group = {'bla': '', 'elements': []} 
     else: 
      if 'a' in item: 
       group['elements'].append(item[0]) 
      else: 
       # Make it DRY <--------------------------------------- 
       if len(group['elements']) > 0: 
        groups.append(group) 
        group = {'bla': '', 'elements': []} 

    # Make it DRY <---------------------------------------  
    if len(group['elements']) > 0: 
       groups.append(group) 
       group = {'bla': '', 'elements': []} 

print(groups) 

修改这些三线,

注意:做任何事情,但示例代码结构不能改变

对不起,我的错误。

+1

第一事物优先:*使用四个空格进行缩进*。但是,你不能把它包装在一个函数中吗? –

+0

对不起。实际上我使用在线ide。这就是为什么2个空格。现在更新 –

回答

1

将该代码放入函数中,并随时调用它。但严重的是,4空格缩进。

collection_of_items = [ 
    ['strong', 'a', ['a'], '', 'strong', ['a'], ['a'], 'a', 'a', [], ''], 
    ['strong', 'a', ['a'], '', 'strong', 'a'] 
] 

groups = [] 

def my_func(g): 
    if len(g['elements']) > 0: 
    groups.append(g) 
    g = {'bla': '', 'elements': []} 
    return g 

for items in collection_of_items: 
    group = {'bla': '', 'elements': []} 
    for item in items: 
    if hasattr(item, 'lower'): 
     if item == 'strong': 
     group['bla'] = item 
     elif item =='a': 
     group['elements'].append(item) 
     elif item == '': 
     group = my_func(group) 
    else: 
     if 'a' in item: 
     group['elements'].append(item[0]) 
     else: 
     group = my_func(group) 

    group = my_func(group) 

print(groups) 
+0

可以将这整个代码包含在另一个函数内 –

+0

您的意思是,所有的代码在'cllection_of_items:'循环中的项目? – ODiogoSilva

+0

我的意思是整个代码将在另一个函数中。像 'def你好: //代码去这里' –