简体   繁体   English

使用if / else的嵌套列表理解

[英]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] . 我有一个函数,该函数采用诸如'1,3-5,7,19'之类的格式的字符串,并将输出列表[1, 3, 4, 5, 7, 19] 1、3、4、5、7、19 [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. 但是这些是SyntaxError。 Moving the if/else to the front of the comprehension as 将if / else移至理解的最前面

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. 导致IndexError:列表索引超出范围。

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. 我已经有一个可以很好地处理它的函数并且更具可读性,但是我只是很好奇这是否可以在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: 使用re.sub()函数的替代解决方案:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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