Search code examples
pythonregexfor-loopcad

Python - passing regex result to a list


I am trying to pass the results of a regex findall() function to a list. The code I am using to do this is as follows:

#iterate DoL, find fobIDs and use to find edgeloop IDs
for key, val in DoL.items():
    fobId = val["FaceOuterBound"]
    edgeloop_txt = re.findall(r'\n#'+str(fobId)+r'\D*#(\d+).*;', text)
    edgeloops = [int(edgeloop) for edgeloop in edgeloop_txt]
    print(edgeloops)

The for loop is iterating through a dictionary and changing fobId each time, which is generating a different match each time. The output currently looks like this:

[159]
[328]
[37]
[18]
...

However, I want it to look like this instead:

[159, 328, 37, 18,....]

I'm guessing it has something to do with the for loop changing the variable edgeloop_txt each time but I'm unsure of how to avoid that.


Solution

  • Right now you are creating a new array and just printing it each time through the loop. Try something like this:

    total_array = []
    
    for key, val in DoL.items():
        fobId = val["FaceOuterBound"]
        edgeloop_txt = re.findall(r'\n#'+str(fobId)+r'\D*#(\d+).*;', text)
        total_array += [int(edgeloop) for edgeloop in edgeloop_txt]
    print(total_array)
    

    This will loop through your items, continually adding to total_array, and print the entire array when the loop is complete.