Попробуйте этот код:
single_lines = []
blocks = []
block = []
block_position = 0
for line in lines.splitlines():
try:
position = line.index('#') # Find the index of the first #
except ValueError:
position = -1
line = line.lstrip()
if line.startswith('#'):
# If current block position match the new one
if block_position == position:
# Part of the same block, adding to the list
block.append(line)
else:
# adding the previous block
if len(block) > 0:
if len(block) == 1:
single_lines.append(block)
else:
blocks.append(block)
# Starting a new block
block = [line]
block_position = position
else:
# Means that there is no # in the line
if len(block) > 0:
# If block was not empty we are closing it
if len(block) == 1:
single_lines.append(block)
else:
blocks.append(block)
block_position = 0
block = []
else:
# Validation if at the end of the loop we still have a block that was not closed
if len(block) > 0:
if len(block) == 1:
single_lines.append(block)
else:
blocks.append(block)
Решение для форматирования печати:
print('Total of Blocks: {}'.format(len(blocks)))
print('Total of single lines: {}'.format(len(single_lines)))
for idx, block in enumerate(blocks):
print('Block {} - contains {} lines :\n{}'.format(idx, len(block), '\n'.join(block)))
Ввод 1 :
# a
# b
# c
Line 1
Line 2
Line 3
# d
# e
f
Выход 1 :
[['# a', '# b', '# c'], ['# d'], ['# e']]
Ввод 2:
# a
# b
# c
Line 1
Line 2
Line 3
# d
# e
# f
f
# g
# h
Выход 2:
[['# a', '# b', '# c'], ['# d', '# e'], ['# f'], ['# g', '# h']]
Выход 2: с форматированием:
Total of Blocks: 3
Total of single lines: 1
Block 0 - contains 3 lines :
# a
# b
# c
Block 1 - contains 2 lines :
# d
# e
Block 2 - contains 2 lines :
# g
# h