Abdullah Mallik
Abdullah Mallik

Reputation: 817

How can i make these 3 lines of code more DRY

this code:

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

Repeated 3 times in the example below. i want to make it in 1 line (atleast make it less). is it possible to do? then how can I do that?

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)

modify those 3 lines,

Note: Do anything but structure of the example code can't be changed

Sorry for mistakes.

Upvotes: 0

Views: 70

Answers (1)

ODiogoSilva
ODiogoSilva

Reputation: 2414

Put that code in a function, and call it whenever you want. But seriously, 4 space indent.

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)

Upvotes: 1

Related Questions