2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
一些修復(fù):
str.split()
返回一個(gè)列表,無需將其結(jié)果放入list
parse_ranges()
不返回任何內(nèi)容,為什么要打印它?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=" ~ ")
輸出('~'作為分隔符添加,因此很清楚,產(chǎn)生的元素的“邊界”在哪里):
# 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貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果需要,您可以將流程拆分為任意多個(gè)生成器步驟,例如:
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]
如果您確實(shí)愿意,您甚至可以將其拆分為更多步驟(拆分為多個(gè)部分,轉(zhuǎn)換為數(shù)字,轉(zhuǎn)換為范圍對象,獲取數(shù)字)。
添加回答
舉報(bào)