使用生成器表达式有什么问题? [英] What's wrong with my use of generator expression?
问题描述
我有以下代码,其中我尝试将范围的字符串表示形式转换为数字列表.例如,如果输入为'0-0,3-5,7-10'
,则预期输出为[0,3,4,5,7,8,9,10]
.但是,我在以下位置出现了错误:
I have the following code, in which I try to convert a string representation of ranges to a list of numbers. For example, if the input is '0-0,3-5,7-10'
the expected output is [0,3,4,5,7,8,9,10]
. However, I got an error at:
for l,h in r.split('-')
表示没有足够的值可解压.我的理由是,r
的格式应为'x-y'
,因此,如果将其除以'-'
,则应该返回两个值.怎么了?
which it says not enough values to unpack. My reasoning is that, r
should have the form 'x-y'
, so if I split it by '-'
, I should get two values back. What's wrong with that?
def parse_ranges(ranges):
"""Return a list of numbers corresponding to number ranges in a string"""
g = (
(l,h)
for r in ranges.split(',')
for l,h in r.split('-')
)
return (x
for range_tuple in g
for l,h in range_tuple
for x in range(int(l), int(h)+1)
)
parse_ranges('0-5,8-10,11-13')
推荐答案
您的循环太多了.由于您试图将两个数字保持在一起,因此不需要第二个嵌套循环.第二个是将结果展平:
You've got a loop too many. Since you're trying to keep the two numbers together you don't need a second nested loop. The second one is flattening the results:
>>> [x for r in s.split(',') for x in r.split('-')]
['0', '0', '3', '5', '7', '10']
使用一个使数字保持配对:
Use one to keep the numbers paired:
>>> [r.split('-') for r in s.split(',')]
[['0', '0'], ['3', '5'], ['7', '10']]
然后,通过第二个理解,可以通过将l
和h
拆包就位来组合前两个for
循环.
Then with the second comprehension you can combine the first two for
loops by unpacking l
and h
in place.
return (x
for l,h in g
for x in range(int(l), int(h)+1)
)
这篇关于使用生成器表达式有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!