簡體   English   中英

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

[英]Python print format of integers and string mix

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) 和我希望它是 1-7,9-12,14-19,300

嘗試這個

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)

這對您有幫助嗎:(最后,您可以根據需要修改最終的連接格式...)


    >>> 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指出當前 integer 比前一個大一,也處理到達line尾並繼續序列的情況。 第三個說明一個序列已被破壞,並添加了 output 。 最后一個else塊在非序列之后添加當前值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM