vendredi 6 octobre 2017

Nested List Comprehension with if/else

I have a function that takes a string in a format such as '1,3-5,7,19' and will output the list [1, 3, 4, 5, 7, 19].

However, I was thinking that maybe this was simple enough to do with a nested list comprehension.

My original function is:

result = []
for x in row_range.split(','):
    if '-' in x:
        for y in range(int(x.split('-')[0]), int(x.split('-')[1]) + 1)):
            result.append(y)
    else:
        result.append(int(x))

I thought the comprehension would be something like:

result = [y for x in row_range.split(',') if '-' in x else int(x) for y in range(int(x.split('-')[0]), int(x.split('-')[1] + 1)]

or even

result = [y for x in row_range.split(',') if '-' in x for y in range(int(x.split('-')[0]), int(x.split('-')[1] + 1) else int(x)]

but these are SyntaxError. Moving the if/else to the front of the comprehension as

result = [y if '-' in x else int(x) for x in row_range.split(',') for y in range(int(x.split('-')[0]), int(x.split('-')[1]) + 1)]

results in an IndexError: list index out of range.

Is this possible? I already have a function that handles it nicely and is more readable but I am simply curious if this can be accomplished in python.

Aucun commentaire:

Enregistrer un commentaire