我有一个函数混合范围,它使字符串类似于'1,2,4-6,8',并将其转换为'1,2,4,5,6,8'。现在,在输入'1,2,4,5,6,8'并将其转换为'1,2,4-6,8'的情况下,我如何做完全相反的操作呢?函数类型将其转换为int和list (这不是问题,因为我可以将它转换回普通字符串)。
def mixrange(s):
r = []
for i in s.split(','):
if '-' not in i:
r.append(int(i))
else:
l,h = map(int, i.split('-'))
r+= range(l,h+1)
return r发布于 2022-02-18 12:59:41
我觉得这是个不错的练习,所以我解决了。不一定是最简洁的解决方案,但希望能奏效:
s = "1,2,4,5,6,8,11,12,13,14,15,16,22,23"
numbers = [int(e) for e in s.split(",")]
def first_block_end(numbers): # returns the last index of the block of consecutive numbers starting with the first number
if len(numbers) == 1:
return 0
i = 0
while i + 1 < len(numbers) and numbers[i + 1] == numbers[i] + 1:
i += 1
return i
result = []
while len(numbers) > 0:
idx = first_block_end(numbers)
if idx == 0:
result.append(str(numbers[0]))
elif idx == 1:
result.append(str(numbers[0]))
result.append(str(numbers[1]))
else:
result.append(str(numbers[0]) + "-" + str(numbers[idx]))
numbers = numbers[idx + 1:]
result = ",".join(result)
print(result)发布于 2022-02-18 14:05:17
以下是另一条很短的路:
def to_range(s):
if not s: # handle empty string
return ''
prev = float('-inf')
out = []
i = 0
for v in map(int,s.split(',')): # loop over each number
if v == prev+1: # if previous + 1, count
i+=1
else: # new group
if i>0: # if successive add last as range
out[-1] += f'-{prev}'
out.append(str(v)) # add next start
i = 0
prev = v
if i>0: # handle last number
out[-1] += f'-{prev}'
return ','.join(out) # return as string示例:
to_range('1,2,4,5,6,8,1,2,3,4')
# '1-2,4-6,8,1-4'
to_range('1,2,3,3')
# '1-3,3'发布于 2022-02-18 12:49:30
编辑:我根据您的需要编辑了函数,正如我所理解的。如果元素的增量为1,则应该将其显示为范围。这就是我所实现的。
def exact_oposite(nums):
data_str = nums.split(',')
start = 0
end = None
output_list = []
lst_len = len(data_str)
for index, num in enumerate(data_str):
if index+1 != lst_len:
if int(data_str[index+1]) - int(num) > 1:
if start is None:
start = data_str[index+1]
output_list.append(num)
else:
end = index
if start == end:
output_list.append(data_str[start])
else:
if end-start <= 1:
output_list.append(data_str[start])
output_list.append(data_str[end])
else:
output_list.append(f'{data_str[start]}-{data_str[end]}')
start = index+1
end = None
else:
if start is None and end is None:
output_list.append(num)
else:
if end is None and start is not None:
end = index
if start == end:
output_list.append(data_str[start])
else:
if end-start <= 1:
output_list.append(data_str[start])
output_list.append(data_str[end])
else:
output_list.append(f'{data_str[start]}-{data_str[end]}')
else:
output_list.append(num)
return ",".join(output_list)https://stackoverflow.com/questions/71173598
复制相似问题