2 回答
TA贡献1804条经验 获得超2个赞
一些修复:
str.split()
返回一个列表,无需将其结果放入list
parse_ranges()
不返回任何内容,为什么要打印它?range(int(4), int(4) + 1)
不会回来,[4, 4]
但只会[4]
def parse_ranges(range_string):
temp = (map(int, c.split("-")) for c in range_string.split(","))
# yield all the numbers (yield from 'flattens' the result)
for start, stop in temp:
yield from range(start, stop + 1)
# or to yield lists
# for start, stop in temp:
# yield list(range(start, stop + 1))
print(*parse_ranges("1-2,4-4,8-10"), sep=" ~ ")
print(*parse_ranges("0-0,4-8,20-21,43-45"), sep=" ~ ")
输出('~'作为分隔符添加,因此很清楚,产生的元素的“边界”在哪里):
# yield from range(start, stop + 1)
1 ~ 2 ~ 4 ~ 8 ~ 9 ~ 10
0 ~ 4 ~ 5 ~ 6 ~ 7 ~ 8 ~ 20 ~ 21 ~ 43 ~ 44 ~ 45
# yield list(range(start, stop + 1))
[1, 2] ~ [4] ~ [8, 9, 10]
[0] ~ [4, 5, 6, 7, 8] ~ [20, 21] ~ [43, 44, 45]
TA贡献2019条经验 获得超9个赞
如果需要,您可以将流程拆分为任意多个生成器步骤,例如:
def get_ranges(string):
for part in string.split(","):
yield [int(number) for number in part.split("-")]
def get_numbers(ranges):
for start, stop in ranges:
yield from range(start, stop + 1)
用法:
>>> list(get_numbers(get_ranges("1-2,4-4,8-10")))
[1, 2, 4, 8, 9, 10]
如果您确实愿意,您甚至可以将其拆分为更多步骤(拆分为多个部分,转换为数字,转换为范围对象,获取数字)。
添加回答
举报