Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a list with strings and nested lists of strings into a flat list

I am writing a program that manipulates strings in a file. I want to simply add the literals (strings, such as SUB =X'1D' that assemble into =X'1D' BYTE X'1D') above an ' LTORG' to my testfile.

The problem is I collected the literals above each LTORG as a list inserted them as a list. I would like to insert literals one at a time.

I have this output that is :

[' START 100', " SUB =X'1D'", ' LTORG', '["=X\'1D\' BYTE X\'1D\'"]', ' RESW 
   20', " SUB =X'0259'", " ADD =C'12345'", " MUL =X'4356'", " SUB =X'69'", ' 
   LTORG', '["=X\'0259\' BYTE X\'0259\'", "=C\'12345\' BYTE C\'12345\'", 
   "=X\'4356\' BYTE X\'4356\'", "=X\'69\' BYTE X\'69\'"]', " ADD =C'05'", ' 
   END EXA']
def handle_LTORG(self, testfile):

    myfile.testfile = testfile

    for index, line in enumerate(myfile.testfile):
        line = line.split(" ", 3)
        if len(line) > 2:
            if line[2].startswith("=X") or line[2].startswith("=C"):
                raw_literal = line[2]
                instruction = 'BYTE'
                operand = line[2][1:]
                literal = [raw_literal, instruction, operand]
                literal = ' '.join(literal)
                myfile.literals.append(literal)
        if line[1] == 'LTORG':
            if myfile.literals is not None:
                myfile.testfile.insert(index + 1, str(myfile.literals))
                myfile.literals.pop(0)

The second-last line is mainly producing the issue. It adds the literals collected in a list and inserts them as a packed list rather than one string per line.

I want it to look like this:

[' START 100', " SUB =X'1D'", ' LTORG', '"=X'1D' BYTE X'1D'"', ' RESW 20', " SUB =X'0259'", " ADD =C'12345'", " MUL =X'4356'", " SUB =X'69'", ' LTORG', '"=X'0259' BYTE X'0259'", "=C'12345' BYTE C'12345'", "=X'4356' BYTE X'4356'", "=X'69' BYTE X'69'", " ADD =C'05'", ' END EXA']
like image 369
asultan904 Avatar asked Mar 31 '19 07:03

asultan904


1 Answers

i'd try to use something like the top comment here How to make a flat list out of list of lists?

list = ['whatever',['1','2','3'],'3er']
flat_list = []
for member in list:
    if type(member) is list:
        for item in member:
            flat_list.append(item)
    else:
        flat_list.append(member)
like image 126
ConscriptMR Avatar answered Oct 28 '22 13:10

ConscriptMR