整数和字符串混合的Python打印格式

2024-09-27 00:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

line = [1,2,3,4,5,6,7,9,10,11,12,14,15,16,17,18,19,300]


GroupCount = 0
FormatDesignators =line[0]

for i in range(1 ,len(line)):
    if line[i] != line[i - 1] + 1:
        if GroupCount >= 1:
            FormatDesignators = FormatDesignators,'-', line[i - 1]
            FormatDesignators = FormatDesignators,',',line[i]
            GroupCount = 0
    else:
        GroupCount = GroupCount + 1
print(FormatDesignators)


if GroupCount >= 1:
    FormatDesignators = FormatDesignators,"-",line[i]
    print (FormatDesignators)

现在它正在输出:

((((((1, '-', 7), ',', 9), '-', 12), ',', 14), '-', 19), ',', 300) and I want it to be 1-7,9-12,14-19,300


Tags: andtoinforleniflinerange
3条回答

这对您有帮助吗:(最后,您可以根据自己的喜好在格式方面修改最终的连接…)


    >>> line = [1,2,3,4,5,6,7,9,10,11,12,14,15,16,17,18,19,300]
    >>> starts = [x for x in line if x-1 not in line]
    >>> ends = [y for y in line if y+1 not in line]
    >>> ranges = list((a,b) for a, b in zip(starts, ends))
    >>> ranges
    [(1, 7), (9, 12), (14, 19), (300, 300)]
    >>> results = [str(a)+'-'+str(b)  for a, b in ranges]

以下方法似乎有效。我试图做一些只在数据中迭代一次的东西:

c = 0
result = ''
current = None
run = False

while c < len(line):

    if current == None:
        result += f'{line[c]}'
    elif line[c] - current == 1:
        run = True
        if c == len(line) - 1:
            result += f'-{line[c]}'
    elif run:
        result += f'-{current},{line[c]}'
        run = False
    else:
        result += f',{line[c]}'

    current = line[c]
    c += 1

print(result)
# 1-7,9-12,14-19,300

第一个if检查是否未看到任何数字,即仅检查第一个数字。第二个if注意到当前整数比前一个大一,当到达line的末尾并继续一个序列时也会处理。第三个注意到一个序列已被破坏,并添加输出。最后一个else块在非序列之后添加当前值

试试这个

line = [1,2,3,4,5,6,7,9,10,11,12,14,15,16,17,18,19,300]


GroupCount = 0
FormatDesignators =line[0]

for i in range(1 ,len(line)):
    if line[i] != line[i - 1] + 1:
        if GroupCount >= 1:
            FormatDesignators = f'{FormatDesignators} - {line[i - 1]},'
            FormatDesignators = f'{FormatDesignators} {line[i]}'
            GroupCount = 0
    else:
        GroupCount = GroupCount + 1
print(FormatDesignators)


if GroupCount >= 1:
    FormatDesignators = f'{FormatDesignators} - {line[i]},'
    print (FormatDesignators)

相关问题 更多 >

    热门问题