简体   繁体   中英

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.

You could define a small helper function:

def foo(x):
     x, y  = map(int, x.split('-'))
     return (x, y + 1)

Now, use a list comprehension with a nested loop.

>>> [y for x in row_range.split(',') 
           for y in ([int(x)] if '-' not in x else range(*foo(x)))] 
[1, 3, 4, 5, 7, 19]

Alternative solution with re.sub() function:

import re

row_range = '1,3-5,7,8,10-14,19'   # extended example
cb = lambda r: repr(list(range(int(r.group(1)), int(r.group(2))+1)))[1:-1]
result = [int(i) for i in re.sub(r'(\d+)-(\d+)', cb, row_range).split(',')]

print(result)

The output:

[1, 3, 4, 5, 7, 8, 10, 11, 12, 13, 14, 19]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM