Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return only index zero in a list comprehension

To create a list with the values that I retrieve from a spreadsheet, I do it like this:

result = {'range': 'Winning_Margin!G2:O1000', 'majorDimension': 'ROWS', 
          'values': [['10148734', 'CD Olimpia', 'CD Vida', '1', 
                      '71', '85', '14.00', '1.40', '2-0'], 
                     ['', '', '', '', '', '', '', '', ''], 
                     ['10024627', 'Sporting Kansas City', 'FC Dallas', 
                      '2', '35', '1', '-34.00', '2.88']]}

for a in result["values"]:
    a.extend([''] * (max(map(len, result["values"])) - len(a)))

spreadsheets_match_id = [item for sublist in result["values"] for item in (sublist or ['']) if sublist[-1] != '']

This way returns the entire index:

['10148734', 'CD Olimpia', 'CD Vida', '1', '71', '85', '14.00', '1.40', '2-0']

But my need is just the first index of each list of list, in this case the result is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['10148734']

Tried to make each item become item[0] but when trying to do that, it either says that item doesn’t exist or returns the first letter of each of the list’s indexes within the list like ['1', 'C', 'C', '1', '7', '8', '1', '1', '2'].

>Solution :

Edit:
You can check if the last element of the sublist is '' or not and keep the first elements of the ones that aren’t:

out = [sublist[0] for sublist in result["values"] if sublist[-1] !='']

Old answer:

IIUC, you want to get the first element of a sublist that is not '', right? Then you can create a single element list in a list comprehension and iterate over it in a nested loop to check if it is '' or not:

out = [item for sublist in result["values"] for item in [sublist[0]] if item !='']

Output:

['10148734', '10024627']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading