Home > OS >  Parse a list into a list of lists in python
Parse a list into a list of lists in python

Time:07-22

I am trying to figure out how to parse a list into a list of lists.

            tileElements = browser.find_element(By.CLASS_NAME, 'tile-container')
            tileHTML = (str(tileElements.get_attribute('innerHTML')))
            tileNUMS = re.findall('\d ',tileHTML)
            NumTiles = int(len(tileNUMS)/4)
            #parse out list, each 4 list items are one tile
            print(str(tileNUMS))
            print(str(NumTiles))
            
            TileList = [[i j for i in range(len(tileNUMS))]for j in range (NumTiles)]
            print(str(TileList))

The first part of this code works find and gives me a list of Tile Numbers:

['2', '3', '1', '2', '2', '4', '4', '2']

However, what I need is a list of lists made out of this and that is where I am getting stuck. The list of lists should be 4 elements long and look like this:

[['2', '3', '1', '2'] , ['2', '4', '4', '2']]

It should be able to do this for as many tiles as there are in the game (up to 19 I believe). It would be really nice if when the middle numbers are repeated that the two outside numbers are replaced with the latest value from the source list.

CodePudding user response:

You can use a list comprehension to get slices from the list like so.

elements = ['2', '3', '1', '2', '2', '4', '4', '2']
size = 4
result = [elements[i:i size] for i in range(0, len(elements), size)]

(By the way, there's no need to cast things into str to print them, and tileHTML is probably already a string, too.)

  • Related