可以说我的绳索长度为0-5000。我想将这条绳子分开,这样就可以减少下面显示的列表中的间隔,并返回其余部分:

我的清单:

['HE670029', '4095', '4096']
['HE670029', '4098', '4099']
['HE670029', '4102', '4102']


所需的输出(不必是列表,可以将其写入新行中的每个list文件):

['HE670029', '0', '4094']
['HE670029', '4097', '4097']
['HE670029', '4100', '4101']
['HE670029', '4103', '5000']


我尝试操作字典,但没有成功。我不知道如何将其转换为允许我执行所需操作的格式。

最佳答案

它不是很漂亮,但是可以工作:

sections_to_cut = [
        ['HE670029', '4095', '4096'],
        ['HE670029', '4098', '4099'],
        ['HE670029', '4102', '4102']
    ]

ropes = {}
for rope in sections_to_cut:
    if rope[0] not in ropes: # could use default dict instead
        ropes[rope[0]] = []
    ropes[rope[0]].append((int(rope[1]), int(rope[2])))

cut_ropes = []

for rope_name, exclude_values in ropes.items():
    sorted_ex = sorted(exclude_values, key=lambda x: x[0])
    a = 0
    for i in sorted_ex:
        cut_ropes.append([rope_name, str(a), str(i[0]-1)])
        a = i[1] + 1
    cut_ropes.append([rope_name, str(a), str(5000)])

print(cut_ropes)
# [['HE670029', '0', '4094'], ['HE670029', '4097', '4097'], ['HE670029', '4100', '4101'], ['HE670029', '4103', '5000']]

08-25 14:30
查看更多