pythonarraysstringlistpython-2.7

Python - Select all elements a list of a list


I want to write a series of code (it may be func, loop or etc.) to get first 6 chars of each list of every list.

It looks like this: http://www.mackolik.com/AjaxHandlers/FixtureHandler.aspx?command=getMatches&id=3170&week=1

this is the first list of my list, second can be found here: week=2.

It goes through 11.

In addition to this, each list element of my list differentiates.

Can you help me or give an idea to deal with.


Solution

  • It looks like you you have a wretched multi-level data-in-string-in-list-of-list structure:

    data = [
        ["[[342212,'21/02',,'MS'], [342276,'21/02',,'MS']]"],
        ["[[342246,'21/02',,'MS']]"]
    ]
    

    and you want to collect [342212, 342276, 342246].

    To do this properly you pretty much have to parse each string to an actual data structure; this is complicated by the fact that consecutive commas (,,) are not valid Python syntax

    import ast
    
    def fix_string(s):
                                        # '[,,,]'
        s = s.replace("[,", "[None,")   # '[None,,,]'
        s = s.replace(",,", ", None,")  # '[None, None,,]'
        s = s.replace(",,", ", None,")  # '[None, None, None,]'
        s = s.replace(",]", ", None]")  # '[None, None, None, None]'
        return s
    
    data = [ast.literal_eval(fix_string(s)) for row in data for s in row]
    

    which gives us

    data = [
        [
            [342212,'21/02', None, 'MS'],
            [342276,'21/02', None, 'MS']
        ],
        [
            [342246,'21/02', None, 'MS']
        ]
    ]
    

    then you can collect values like

    ids = [item[0] for batch in data for item in batch]